Swift带来很多确实很棒的特性,使得很难再回到Objective-C。主要的特性是安全性,不过这也被看成是一种额外副作用。
带类型接口的强型别 Swift有强型别,这意味着除非你要求,不然Swift不会为你做类型之间的转换。所以,例如你无法把Int型赋给Double型。你不得不首先转换类型: let i: Int = 42
let d: Double = Double(i)
或者你必须给Double类扩展一个方法用来转换Int型: extension Double {
func __convert(i: Int) -> Double {
return Double(i)
}
}
let another_d: Double = i
强型别对于安全性是非常非常有利的。但是,如果它没有为你给类型接口添加许多类型信息的话,它也可能变成有一点令人生畏的事情,有点像是在写脚本语言。 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 + " ")
}
如果你想要创建一个包含很多类型(无共同祖先)的数组,你应该用枚举(它可以包含值,见如下)。如果你想要它能够包含所有值,你可以用Any型。如果想让它包含任何Objective-C的类型,那就用AnyObject型。 请注意类型接口不会在申明函数的时候为你添加类型。你必须明确地说明你所申明函数的类型。
Blocks Swift 中的Blocks很像Objective-C中的Blocks, 不过有两点不同: 类型推断和避免weakify dance.
对于类型推断,你不必每次写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], <)
访问 Closures 了解更多blocks信息。
除此之外,Objectvie-C 的weakify dance有点容易,只需在block的开始处加上 [unowned self] 或 [weak self] 即可。 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
}
请注意Introduction post文章中介绍了Optional(像上面的callback)。
请参考 ARC 章节来了解更多关于Swift中ARC的信息。
强劲的Enumerations Swift中的枚举比Objective-C中的有很大提高。
修复 Enums Apple一直提倡显示的提供枚举类型的大小,不过被Objective-C搞乱了: // Apple recommended enum definition in Objective-C
typedef NS_ENUM(NSInteger, UIViewAnimationCurve) {
UIViewAnimationCurveEaseInOut,
UIViewAnimationCurveEaseIn,
UIViewAnimationCurveEaseOut,
UIViewAnimationCurveLinear
};
// Previous Apple recommended enum definition in Objective-C. No link between
// enum values and theUIViewAnimationCurve type.
typedef enum {
UIViewAnimationCurveEaseInOut,
UIViewAnimationCurveEaseIn,
UIViewAnimationCurveEaseOut,
UIViewAnimationCurveLinear
};
typedef NSInteger UIViewAnimationCurve;
// Traditional enum definition in Objective-C. No explicit fixed size.
typedef enum {
UIViewAnimationCurveEaseInOut,
UIViewAnimationCurveEaseIn,
UIViewAnimationCurveEaseOut,
UIViewAnimationCurveLinear
} UIViewAnimationCurve; Swift中的修复: enum UIViewAnimationCurve : Int {
case EaseInOut
case EaseIn
case EaseOut
case Linear
}
拓展Enums Enums 在Swift中更进一步,只作为一个独立的选项列表。你可以添加方法(以及计算属性): enum UIViewAnimationCurve : Int {
case EaseInOut
case EaseIn
case EaseOut
case Linear
func typeName() -> String {
return "UIViewAnimationCurve"
}
}
使用类型拓展,你可以向枚举中添加任何你想要的方法: extension UIViewAnimationCurve {
func description() -> String {
switch self {
case EaseInOut:
return "EaseInOut"
case EaseIn:
return "EaseIn"
case EaseOut:
return "EaseOut"
case Linear:
return "Linear"
}
}
}
向Enums中添加值
Swift中的枚举跟进一步,允许每一个独立的选项都有一个对应的值: enum Shape {
case Dot
case Circle(radius: Double) // Require argument name!
case Square(Double)
case Rectangle(width: Double, height: Double) // Require argument names!
func area() -> Double {
switch self {
case Dot:
return 0
case Circle(let r): // Assign the associated value to the constant 'r'
return π*r*r
case Square(let l):
return l*l
case Rectangle(let w, let h):
return w*h
}
}
}
var shape = Shape.Dot
shape = .Square(2)
shape = .Rectangle(width: 3, height: 4) // Argument names required
shape.area() 如果你喜欢,你可以把它当做一个安全的union类型。或者只用枚举应该做的事情。
Enumerations 文章介绍了更多关于Apple对此的看法。
Swift Switch语句 就像你看到的,Swift中switch语句有很多优化。 隐式的fall-through行为已经改为了显示的: var (i, j) = (4, -1) // Assign (and create) two variables simultaneously
switch i {
case 1:
j = 1
case 2, 3: // The case for both 2 and 3
j = 2
case 4:
j = 4
fallthrough
case 5:
j++
default:
j = Int.max // The Swift version of INT_MAX
}
就像前面看到的,Switch 语句可以访问枚举的关联值,不过它还可以做更多: var tuple: (Int, Int) // Did I mention that Swift has tuples? :-)
var result: String
tuple = (1,3)
switch tuple {
case (let x, let y) where x > y:
result = "Larger"
case (let x, let y) where x < y:
result = "Smaller"
default:
result = "Same"
}
甚至可以使用String: var s: String = "Cocoa"
switch s {
case "Java": s = "High caffeine"
case "Cocoa": s = "High sugar"
case "Carbon": s = "Lots of bubbles"
default: ()
}
另外,如果你觉得他可以使你的代码更可读,你可以重载~=操作符来改变switch语句的行为。 func ~=(pattern: String, str: String) -> Bool {
return str.hasPrefix(pattern)
}
var s = "Carbon"
switch s {
case "J": s = "High caffeine"
case "C": s = "No caffeine"
default: ()
}
你可以从 Conditional Statements 这篇文章中了解更多关于switch语句的知识。
类与结构体 类似于C++,Swift的类与结构体初看是一样的: 04 | init(_ color: String) { |
07 | func description() -> String { |
08 | return "apple of color \(color)" |
18 | init(_ color: String) { |
21 | func description() -> String { |
22 | return "orange of color \(color)" |
24 | mutating func enripen() { |
主要的不同点在于类是(和块相似的)引用类型,而结构体是(和枚举相似的)数值类型。所以两个变量能够指向同一个(类的)对象,而把一个结构体赋给另外一个变量则必须做一个此结构体的(缓慢的)拷贝。关键词'mutating'告诉调用者enripen()方法不能被常结构体调用。把一个常引用mutating给一个类对象则没有问题。
Swift中大多数内建类型实际上都是结构体。甚至Int型也是。通过点击Cmd你能够看到内建类型的申明,比如Int型的Swift(或者Playground)源码。数组和词典类型也是结构体,但是数组在某些方面表现得像是引用类型:赋值数组并不拷贝每一个元素,实际上你可以更新常数组只要元素的个数保持不变。
在苹果的文档中,你可以读到更多关于Collection Types的内容。
对象的生命周期 另一个类与结构体的不同是类可以被子类化。 雷和结构体都可以被拓展,并且实现protocol,但是只用类可以继承其他类。 01 | class Pineapple : Apple { |
08 | convenience init(ripe: Bool) { |
17 | println( "Pineapple down" ) |
19 | override func description() -> String { |
20 | return "pine" + super.description() |
22 | override func enripen() { |
就像你看到的,Swift为继承添加了一点更有趣的需要学习的东西。对于初学者来说,你需要清除你覆盖父类中某个方法的意图。如果你想阻止子类覆盖一些东西,你可以在一个单独声明或整个类的前面加上@final属性。阅读 Apple’s documentation了解更多。
初始化 Swift的对象分两步进行初始化: 首先对象必须是有效的,然后它能被替换。 03 | init(foot_size: Double) { |
05 | addGrowthCompensation() |
07 | func addGrowthCompensation() { |
使对象有效必须要调用一个超级类指定的init()方法。类可以同时拥有指定的以及便捷的(用关键词'convenience'标记)初始化方法。便捷初始化方法调用同一个类中的其他初始化方法(最终还是一个指定的初始化方法),而指定的初始化方法调用超级类的初始化方法。 如果你给所有的超级类指定初始化方法添加初始化方法,你的类也会自动继承所有便捷初始化方法。如果没有添加任何指定的初始化方法,你的类则继承超级类的所有(指定的和便捷的)初始化方法。 深入阅读请参见Initialization。
类型转换 类之间的转换,特别是向下转换,你可以使用"is","as?"和"as"关键词: 01 | let apple: Apple = Pineapple() |
03 | let exotic: Bool = apple is Pineapple |
05 | let pineappleOption: Pineapple? = apple as? Pineapple |
06 | let pineapple: Pineapple = apple as Pineapple |
08 | if let obj = apple as? Pineapple { |
想了解更多这方面内容请参见Type Casting一章.
泛型 泛型是Swift的一个加分的特点。他们看起来有一点像C++里面的模板,但是有更强的型别,也更简单(更简单使用,功能稍逊)。 02 | protocol DoubleConvertible { |
03 | @prefix func +(v: Self) -> Double |
05 | @prefix func +(v: Int) -> Double { return Double(v) } |
06 | extension Double: DoubleConvertible {} |
07 | extension Int: DoubleConvertible {} |
13 | class var dimensions: Int { get } |
14 | func getCoordinate(dimension: Int) -> T |
18 | struct Pythagoras<P1: PointTraits, P2: PointTraits where P1.T: DoubleConvertible, P2.T: DoubleConvertible> { |
19 | static func apply(a: P1, b: P2, dimensions: Int) -> Double { |
23 | let d: Double = +a.getCoordinate(dimensions-1) - +b.getCoordinate(dimensions-1) |
24 | return d * d + apply(a, b: b, dimensions: dimensions-1) |
26 | static func apply(a: P1, b: P2) -> Double { |
27 | let dimensions = P1.dimensions |
28 | assert (P2.dimensions == dimensions) |
29 | return apply(a, b: b, dimensions: dimensions) |
33 | import func Foundation. sqrt |
35 | func distance<P1: PointTraits, P2: PointTraits where P1.T: DoubleConvertible, P2.T: DoubleConvertible>(a: P1, b: P2) -> Double { |
36 | assert (P1.dimensions == P2.dimensions) |
37 | return sqrt (Pythagoras.apply(a, b: b)); |
41 | struct Point2D<Number> : PointTraits { |
42 | static var dimensions: Int { return 2 } |
43 | var x: Number, y: Number |
44 | func getCoordinate(dimension: Int) -> Number { return dimension == 0 ? x : y } |
46 | let a = Point2D(x: 1.0, y: 2.0) |
47 | let b = Point2D(x: 5, y: 5) |
48 | Pythagoras.apply(a, b: b) |
52 | extension UIColor : PointTraits { |
53 | class var dimensions: Int { return 4 } |
54 | func getCoordinate(dimension: Int) -> Double { |
55 | var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 |
56 | getRed(&red, green: &green, blue: &blue, alpha: &alpha) |
65 | distance(UIColor.redColor(), UIColor.orangeColor()) |
以上代码是受Boost中的Design Rationale的启发.几何的C++库。Swift中的泛型功能不是那么强,但是却能使源码比C++中泛型更具阅读性。
Swift的泛型是通过类型参数化的。每个参数类型要求实现一个特定的协议或者继承自一个特定的基类。在申明参数类型后,有一个可选的"where"项目能用于给这个类型(或者是他们的内部类型,就如上面那个PointTraits协议中的别名'T')添加额外的需求。这个"where“也能要求两种类型是相等的。
苹果有更多更完整的Generics章节。
选定Swift 现在你已经准备好了去看各种各样的源码了,甚至可以自己写了 :-)
在把你自己留在一个新的大的Swift未知大陆之前,我有几个最终的建议: Apple推荐你使用Int作为所有Integer类型,即使你之前用无符号数的地方。“只有在你真的需要一个与平台原生大小想相同的无符号integer类型时再使用UInt类型.” 如果你想知道@private和al.在哪:好吧,他们还没完成呢,后续版本会加进来的。 如果你创建了一个module,你可以Cmd+单击你的module的名字来查看你的module的自动生成的Swift头。 Swift的modules其实是命名空间,因此在任何东西前加像 CF, NS, UI等的前缀。当创建第三方库是就不是那么绝对必要了。
Enjoy using Swift! |