Questions tagged [swift]
Swift is a general-purpose programming language developed by Apple Inc first released in 2014 for its platforms and Linux. Swift is open-source. Use the tag only for questions about language features or requiring code in Swift. Use the tags [ios], [ipados], [macos], [watch-os], [tvos], [swiftui], [cocoa-touch], and [cocoa] for (language-agnostic) questions about the platforms or frameworks.
swift
333,537
questions
1500
votes
44
answers
524k
views
Passing data between view controllers
I'm new to iOS and Objective-C and the whole MVC paradigm and I'm stuck with the following:
I have a view that acts as a data entry form and I want to give the user the option to select multiple ...
1136
votes
17
answers
375k
views
How do I call Objective-C code from Swift?
In Swift, how does one call Objective-C code?
Apple mentioned that they could co-exist in one application, but does this mean that one could technically re-use old classes made in Objective-C whilst ...
1087
votes
61
answers
672k
views
How to change Status Bar text color in iOS
My application has a dark background, but in iOS 7 the status bar became transparent. So I can't see anything there, only the green battery indicator in the corner. How can I change the status bar ...
1020
votes
20
answers
254k
views
#pragma mark in Swift?
In Objective C, I can use #pragma mark to mark sections of my code in the symbol navigator. Since this is a C preprocessor command, it's not available in Swift. Is there a stand-in for this in Swift, ...
987
votes
9
answers
119k
views
Swift Beta performance: sorting arrays
I was implementing an algorithm in Swift Beta and noticed that the performance was very poor. After digging deeper I realized that one of the bottlenecks was something as simple as sorting arrays. The ...
964
votes
20
answers
671k
views
How to iterate a loop with index and element in Swift
Is there a function that I can use to iterate over an array and have both index and element, like Python's enumerate?
for index, element in enumerate(list):
...
877
votes
19
answers
350k
views
#ifdef replacement in the Swift language
In C/C++/Objective C you can define a macro using compiler preprocessors.
Moreover, you can include/exclude some parts of code using compiler preprocessors.
#ifdef DEBUG
// Debug-only code
#endif
...
838
votes
41
answers
539k
views
Get the length of a String
How do you get the length of a String? For example, I have a variable defined like:
var test1: String = "Scott"
However, I can't seem to find a length method on the string.
830
votes
41
answers
795k
views
Split a String into an array in Swift?
Say I have a string here:
var fullName: String = "First Last"
I want to split the string based on whitespace and assign the values to their respective variables
var fullNameArr = // ...
741
votes
18
answers
297k
views
+50
How do I see which version of Swift I'm using?
I just created a new Swift project within Xcode. I am wondering which version of Swift it's using.
How can I see, in Xcode or the terminal, what version of Swift I am using inside my project?
698
votes
24
answers
356k
views
@selector() in Swift?
I'm trying to create an NSTimer in Swift but I'm having some trouble.
NSTimer(timeInterval: 1, target: self, selector: test(), userInfo: nil, repeats: true)
test() is a function in the same class.
...
686
votes
43
answers
188k
views
iOS 8 UITableView separator inset 0 not working
I have an app where the UITableView's separator inset is set to custom values - Right 0, Left 0. This works perfectly in iOS 7.x, however in iOS 8.0 I see that the separator inset is set to the ...
671
votes
23
answers
742k
views
Convert Int to String in Swift
I'm trying to work out how to cast an Int into a String in Swift.
I figure out a workaround, using NSNumber but I'd love to figure out how to do it all in Swift.
let x : Int = 45
let xNSNumber = x ...
670
votes
34
answers
355k
views
iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta
This crash has been a blocking issue I used the following steps to reproduce the issue:
Create a Cocoa Touch Framework project
Add a swift file and a class Dog
Build a framework for device
Create a ...
655
votes
27
answers
596k
views
How do I check if a string contains another string in Swift?
In Objective-C the code to check for a substring in an NSString is:
NSString *string = @"hello Swift";
NSRange textRange =[string rangeOfString:@"Swift"];
if(textRange.location != NSNotFound)
{
...
654
votes
20
answers
506k
views
How to sort an array of custom objects by property value in Swift
Let's say we have a custom class named imageFile and this class contains two properties:
class imageFile {
var fileName = String()
var fileID = Int()
}
Lots of them are stored in an Array:
...
641
votes
22
answers
420k
views
UITextField text change event
How can I detect any text changes in a textField? The delegate method shouldChangeCharactersInRange works for something, but it did not fulfill my need exactly. Since until it returns YES, the ...
630
votes
19
answers
111k
views
Do Swift-based applications work on OS X 10.9/iOS 7 and lower?
Will Swift-based applications work on OS X 10.9 (Mavericks)/iOS 7 and lower?
For example, I have a machine running OS X 10.8 (Mountain Lion), and I am wondering if an application I write in Swift will ...
625
votes
35
answers
366k
views
UIScrollView Scrollable Content Size Ambiguity
Fellow devs,
I am having trouble with AutoLayout in Interface Builder (Xcode 5 / iOS 7).
It's very basic and important so I think everyone should know how this properly works. If this is a bug in ...
607
votes
42
answers
320k
views
How to enumerate an enum with String type?
enum Suit: String {
case spades = "♠"
case hearts = "♥"
case diamonds = "♦"
case clubs = "♣"
}
For example, how can I do something like:
for suit in Suit {
// do something with ...
602
votes
8
answers
138k
views
How can I make a weak protocol reference in 'pure' Swift (without @objc)
weak references don't seem to work in Swift unless a protocol is declared as @objc, which I don't want in a pure Swift app.
This code gives a compile error (weak cannot be applied to non-class type ...
596
votes
30
answers
139k
views
Using a dispatch_once singleton model in Swift
I'm trying to work out an appropriate singleton model for usage in Swift. So far, I've been able to get a non-thread safe model working as:
class var sharedInstance: TPScopeManager {
get {
...
592
votes
24
answers
525k
views
Any way to replace characters on Swift String?
I am looking for a way to replace characters in a Swift String.
Example: "This is my string"
I would like to replace " " with "+" to get "This+is+my+string".
How can I achieve this?
585
votes
26
answers
295k
views
dispatch_after - GCD in Swift?
I've gone through the iBook from Apple, and couldn't find any definition of it:
Can someone explain the structure of dispatch_after?
dispatch_after(<#when: dispatch_time_t#>, <#queue: ...
583
votes
6
answers
38k
views
Why are emoji characters like 👩👩👧👦 treated so strangely in Swift strings?
The character 👩👩👧👦 (family with two women, one girl, and one boy) is encoded as such:
U+1F469 WOMAN,
U+200D ZWJ,
U+1F469 WOMAN,
U+200D ZWJ,
U+1F467 GIRL,
U+200D ZWJ,
U+1F466 BOY
So it's very ...
571
votes
18
answers
577k
views
How to check if an element is in an array
In Swift, how can I check if an element exists in an array? Xcode does not have any suggestions for contain, include, or has, and a quick search through the book turned up nothing. Any idea how to ...
568
votes
19
answers
692k
views
How to add constraints programmatically using Swift
I'm trying to figure this out since last week without going any step further. Ok, so I need to apply some constraints programmatically in Swift to a UIView using this code:
var new_view:UIView! = ...
566
votes
6
answers
413k
views
Swift: print() vs println() vs NSLog()
What's the difference between print, NSLog and println and when should I use each?
For example, in Python if I wanted to print a dictionary, I'd just print myDict, but now I have 2 other options. How ...
564
votes
34
answers
292k
views
How do I get the App version and build number using Swift?
I have an IOS app with an Azure back-end, and would like to log certain events, like logins and which versions of the app users are running.
How can I return the version and build number using Swift?
563
votes
17
answers
191k
views
Why Choose Struct Over Class?
Playing around with Swift, coming from a Java background, why would you want to choose a Struct instead of a Class? Seems like they are the same thing, with a Struct offering less functionality. Why ...
560
votes
36
answers
747k
views
How would I create a UIAlertView in Swift?
I have been working to create a UIAlertView in Swift, but for some reason I can't get the statement right because I'm getting this error:
Could not find an overload for 'init' that accepts the ...
552
votes
36
answers
599k
views
Rounding a double value to x number of decimal places in swift
Can anyone tell me how to round a double value to x number of decimal places in Swift?
I have:
var totalWorkTimeInHours = (totalWorkTime/60/60)
With totalWorkTime being an NSTimeInterval (double) ...
550
votes
32
answers
411k
views
How to determine the current iPhone/device model?
Is there a way to get the device model name (iPhone 4S, iPhone 5, iPhone 5S, etc) in Swift?
I know there is a property named UIDevice.currentDevice().model but it only returns device type (iPod touch,...
545
votes
23
answers
164k
views
What does an exclamation mark mean in the Swift language?
The Swift Programming Language guide has the following example:
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { println("\(...
544
votes
87
answers
761k
views
Getting error "No such module" using Xcode, but the framework is there
I'm currently coding in Swift, and I've got an error:
No such module Social
But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "...
541
votes
26
answers
431k
views
How to generate a random number in Swift?
I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation? Or is there a library that does this that we can use now?
537
votes
50
answers
232k
views
How to hide UINavigationBar 1px bottom line
I have an app that sometimes needs its navigation bar to blend in with the content.
Does anyone know how to get rid of or to change color of this annoying little bar?
On the image below situation ...
532
votes
23
answers
687k
views
How to find index of list item in Swift?
I am trying to find an item index by searching a list. Does anybody know how to do that?
I see there is list.StartIndex and list.EndIndex but I want something like python's list.index("text").
521
votes
39
answers
751k
views
Loading/Downloading image from URL on Swift
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error:
'imageWithData' is unavailable: use object ...
516
votes
10
answers
68k
views
Why create "Implicitly Unwrapped Optionals", since that implies you know there's a value?
Why would you create a "Implicitly Unwrapped Optional" vs creating just a regular variable or constant?
If you know that it can be successfully unwrapped then why create an optional in the first place?...
513
votes
47
answers
440k
views
Get nth character of a string in Swift
How can I get the nth character of a string? I tried bracket([]) accessor with no luck.
var string = "Hello, world!"
var firstChar = string[0] // Throws error
ERROR: 'subscript' is unavailable: ...
510
votes
12
answers
177k
views
Shall we always use [unowned self] inside closure in Swift
In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide
The speaker said in that case, if we don't use [unowned self] there, it will be a memory leak. Does it mean ...
509
votes
45
answers
503k
views
Close iOS Keyboard by touching anywhere using Swift
I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-C but I have no idea how to do that using Swift? Does anyone know?
501
votes
15
answers
346k
views
How do I concatenate or merge arrays in Swift?
If there are two arrays created in swift like this:
var a:[CGFloat] = [1, 2, 3]
var b:[CGFloat] = [4, 5, 6]
How can they be merged to [1, 2, 3, 4, 5, 6]?
501
votes
19
answers
640k
views
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
My Swift program is crashing with EXC_BAD_INSTRUCTION and one of the following similar errors. What does this error mean, and how do I fix it?
Fatal error: Unexpectedly found nil while unwrapping ...
498
votes
24
answers
533k
views
How does String substring work in Swift
I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing with substrings things got confusing.
Specifically I was trying the following:
let str = ...
496
votes
12
answers
105k
views
The use of Swift 3 @objc inference in Swift 4 mode is deprecated?
Briefly, while using Xcode 9 Beta, I have run into the following warning:
The use of Swift 3 @objc inference in Swift 4 mode is deprecated. Please address deprecated @objc inference warnings, test ...
485
votes
9
answers
247k
views
How do I write dispatch_after GCD in Swift 3, 4, and 5?
In Swift 2, I was able to use dispatch_after to delay an action using grand central dispatch:
var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC)))
...
483
votes
8
answers
196k
views
Static vs class functions/variables in Swift classes?
The following code compiles in Swift 1.2:
class myClass {
static func myMethod1() {
}
class func myMethod2() {
}
static var myVar1 = ""
}
func doSomething() {
myClass....
482
votes
18
answers
272k
views
How do I get a reference to the AppDelegate in Swift?
How do I get a reference to AppDelegate in Swift?
Ultimately, I want to use the reference to access the managed object context.