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.

Leave a rating/review
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Contents

Hide contents

Swift Language FAQ

25 mins

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.
  • weak: You should use weak for references among objects with independent lifetimes.
  • 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.

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!

What's Next?

What is the future of Swift?

This is only version 1, Apple's intentions are clear that they will be iterating on this language.

To get an idea of what may be coming down the pipeline, check out Karol Mazur's excellent summary of posts from Apple to the dev forums.

So be sure to report bugs and request features! There is a lot of room to see improvements before version 1 is officially released.

How will CocoaPods adapt to Swift?

Likely in a similar way. Swift projects still work as Xcode projects and support multiple targets. There is however potential room for improvement with the ability to create modules and custom frameworks.

It is possible that CocoaPods will be reworked to utilize this feature. There are people who have CocoaPods working with Swift projects and the smart people who work on CocoaPods are already discussing this topic.

More Questions?

If you have any questions that were not covered here (I know you do!) please post a comment. I will pick out some of the best ones and update the post with the question and answer - and also give you attribution for asking!

Also, as mentioned earlier, please chime in with any comments or clarifications on the answers listed here and I'll update as appropriate.

Thanks all, and happy Swift'ing!

Chris Wagner

Contributors

Chris Wagner

Author

Over 300 content creators. Join our team.