Swift Language FAQ
Check out our Swift language FAQ, filled with answers to tons of common questions about Apple’s brand new programming language! By Chris Wagner.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Swift Language FAQ
25 mins
- The Basics
- I’m a beginner. Should I learn Objective-C, Swift, or both?
- I’ve been an Objective-C developer for YEARS. Am I now a beginner?
- Will iOS 8 and OS X Yosemite apps only use Swift?
- Does Swift work with other versions of iOS and OS X?
- Is Swift meant to replace Objective-C, or supplement it?
- What is a playground?
- Is the NDA lifted yet?
- How can I learn Swift?
- Will your future books and tutorials use Swift?
- Diving Right In
- Is there anything that Swift can do that Objective-C can’t, and vice-versa?
- Are there any APIs that don’t work with Swift?
- Where are my println() results in my Playground?
- How do I see those cool graphs of values in Playgrounds?
- How do you run the REPL?
- Can you use Swift to call your own Objective-C code or a third party library? If so, how?
- So, arrays can only contain one type of object? What if I want varied types?
- Is the same true for dictionaries? Are dictionaries also strongly typed?
- The Nitty Gritty
- Is there an equivalent to id in Swift?
- How do you do introspection in Swift? (e.g. equivalent of if ([obj isKindOfClass:[Foo class]]) { ... })?
- How do you put bitshifted values inside an enum in Swift? (i.e. MyVal = 1<<5)
- How does Swift work with Grand Central Dispatch?
- What about the internationalization macros from Objective-C?
- Do I need to worry about reference cycles?
- When should I use strong vs. weak vs. unowned references?
- Where are the semi-colons?!
- What are best practices with Swift coding style?
- What's Next?
- What is the future of Swift?
- How will CocoaPods adapt to Swift?
- More Questions?
The Nitty Gritty
Is there an equivalent to id in Swift?
Yes. As mentioned above when an Objective-C API returns id
Swift will substitute with AnyObject
. The AnyObject
type can represent an instance of any class type. There is also Any
which can represent an instance of any type at all (apart from function types).
How do you do introspection in Swift? (e.g. equivalent of if ([obj isKindOfClass:[Foo class]]) { ... })?
You can check the type of a variable or constant using the is
keyword. The compiler is smart enough to let you know if using is
would be redundant. Thanks to type safety in Swift, it is not possible to later assign a different type to the same reference, which makes this possible.
var someValue : Any?
someValue = "String"
if someValue is String {
println("someValue is a String")
} else {
println("someValue is something else")
}
Notice if you try to write...
var someValue = "String"
if someValue is String {
println("someValue is a String")
} else {
println("someValue is something else")
}
You will receive a compiler warning:
Playground execution failed: error: <REPL>:7:14: error: 'is' test is always true
if someValue is String {
How do you put bitshifted values inside an enum in Swift? (i.e. MyVal = 1<<5)
Unfortunately Apple has not clearly addressed this yet. There are some rumors floating around that they are working on making this better. With that said, we need to write code today, right?!
Fellow Tutorial Team Member Chris LaPollo came up with the following solution:.
class MyOptions {
class var None : UInt32 { return 0 }
class var All : UInt32 { return UInt32.max }
class var First : UInt32 { return 1 }
class var Second : UInt32 { return 1<<1 }
class var Third : UInt32 { return 1<<2 }
}
Example usage:
physicsBody.categoryBitMask = MyOptions.First
physcisBody.collisionBitMask = MyOptions.First | MyOptions.Second
Dave Lawson has also written an article on the matter that you may be interested in reading.
For now this is where we are left, hopefully in an upcoming beta seed we will see what Apple has landed on!
How does Swift work with Grand Central Dispatch?
The same way, you can use the C APIs as you did in Objective-C.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
println("test")
});
You can also use the higher level NSOperationQueue
as prescribed by Apple when dealing with concurrency.
What about the internationalization macros from Objective-C?
Similar to the NSLocalizedString set of macros from Objective-C you can prepare for internationalization in Swift code by using the NSLocalizedString(key:tableName:bundle:value:comment:)
method. The tableName
, bundle
, and value
arguments all have default values. So if you're used to using NSLocalizedString
you can write the following.
NSLocalizedString("Hello", comment: "standard greeting")
Do I need to worry about reference cycles?
Absolutely! It is still possible to create a retain cycle when two objects have a strong
reference to each other. To break retain cycles you would use a similar approach that you use in Objective-C. There are three keywords for declaring reference types which are described below; weak
and unowned
will allow you to resolve reference cycles.
When should I use strong vs. weak vs. unowned references?
Strong references cause ARC to retain instances until they are no longer needed. When all strong
references are removed the referenced instance is deallocated.
Note that the strong
reference is implied by default, so you do not explicitly declare it.
When you set a weak
reference to an object, you're saying that it's OK with you if the object is deallocated due to memory pressure. Weak values must always be a variable, defined with var
and must also be Optional using the ?
operator.
Since weak references are optional, you will never end up with a reference to an invalid instance that no longer exists. ARC will automatically set the reference to nil when the referenced instance is deallocated.
The unowned
reference is used whenever a reference will always have a value by design. Swift guarantees that your app will crash if you access an unowned
when it is nil
, which is untrue in Objective-C where the behavior is undefined. Unowned references are also implicitly unwrapped for convenience.
-
strong: You should use
strong
for things you own.Strong references cause ARC to retain instances until they are no longer needed. When all
strong
references are removed the referenced instance is deallocated.Note that the
strong
reference is implied by default, so you do not explicitly declare it. -
weak: You should use
weak
for references among objects with independent lifetimes.When you set a
weak
reference to an object, you're saying that it's OK with you if the object is deallocated due to memory pressure. Weak values must always be a variable, defined withvar
and must also be Optional using the?
operator.Since weak references are optional, you will never end up with a reference to an invalid instance that no longer exists. ARC will automatically set the reference to nil when the referenced instance is deallocated.
-
unowned: You should use unowned for objects with the same lifetime; such as when an object points back to its owner and you wish to avoid a retain cycle.
The
unowned
reference is used whenever a reference will always have a value by design. Swift guarantees that your app will crash if you access anunowned
when it isnil
, which is untrue in Objective-C where the behavior is undefined. Unowned references are also implicitly unwrapped for convenience.
Where are the semi-colons?!
Semi-colons are optional in Swift and Apple suggests you stop using them for readability purposes.
However, sometimes semicolons are still used in Swift, such as in for statements:
for var index = 0; index < 3; ++index { ... }
What are best practices with Swift coding style?
We have put together a rough draft of a Swift style guide which may be useful.
Note that this is a work in progress and we will be updating it as Swift develops and best practices are discovered!