Swift brings many really great features, making it difficult to return to Objective-C. The main feature is security, but this is also seen as an additional side effect.
Strongly typed APIs
Swift has a strong type, which means that, unless required, Swift will not convert between types for you. Therefore, for example, you cannot assign the Int type to the Double type. You have to first convert the type:
- let i: Int = 42
- let d: Double = Double(i)
Or you must extend a method to the Double class to convert the Int type:
- extension Double {
- func __convert(i: Int) -> Double {
- return Double(i)
- }
- }
- let another_d: Double = i
Strong type is very beneficial for security. However, if it does not add a lot of type information to the type interface, it may become a daunting thing, a bit like writing a script language.
- let ary = ["Hello", "world"] // NOTE: 'ary' is of type String[] or Array<String>
- for s in ary { // NOTE: 's' is of type String
- print(s + " ")
- }
If you want to create an array containing many types (without common ancestor), you should use enumeration (which can contain values, as shown below ). If you want it to include all values, you can use the Any type. If you want to include any Objective-C type, use the AnyObject type.
Note that the type interface does not add a type when declaring a function. You must explicitly describe the type of the function you declare.
Blocks
Blocks in Swift is similar to Blocks in Objective-C, but there are two differences: type inference and avoidance of weakify dance.
For type inference, you do not have to include the complete type information every time you write a block:
- sort([2,1,3], {
- (a: Int, b: Int) -> Bool in return a < b
- })
-
- // Using Type Inference
- // Using the Trailing Closures feature
-
- sort([2,1,3]) {
- a, b in return a < b
- }
-
- // Implicit 'return' for single-expression blocks
-
- sort([2,1,3]) { a,b in a<b }
-
- // Shorthand Argument Names
-
- sort([2,1,3]) { $0 < $1 }
-
- // Operators are functions, and functions are blocks too!
-
- let sorted: Int[] = sort([2,1,3], <)
Visit Closures to learn more about blocks.
In addition, the weakify dance of Objectvie-C is a little easy. You only need to add [unowned self] or [weak self] at the beginning of the block.
- class CallbackTest {
- var i = 5
- var callback: (Int -> ())? // NOTE: The optional callback takes an Int
- deinit { // NOTE: This is like -dealloc in Objective-C
- println("Deinit")
- }
- }
-
- var obj = CallbackTest()
- obj.callback = {
- [unowned obj] // NOTE: Without this, deinit() would never be invoked!
- a in
- obj.i = a
- }
Note that the call back on the Optional image is introduced in the Introduction post article ).
Refer to the ARC chapter for more information.