struct与class
“Use struct to create a structure. Structures support many of the same behaviors as classes, including methods and initializers.One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference.”
摘录来自: Apple Inc. “The Swift Programming Language (Swift 3)”。 iBooks.
• 在swift中struct与class具有很多相同点,但其中一个区别是class是引用,struct是copy。
• 继承允许一个类继承另一个类的特征
• 类型转换允许在运行时检查和解释一个类实例的类型
• 解构器允许一个类实例释放任何其所被分配的资源
• 引用计数允许对一个类的多次引用
mutaing与extension
“Notice the use of the mutating keyword in the declaration of
SimpleStructure to mark a method that modifies the structure. The declaration of SimpleClass doesn’t need any of its methods marked as mutating because methods on a class can always modify the class”
注意声明 SimpleStructure 时候 mutating 关键字用来标记一个会修改结构体的方法。 SimpleClass 的声明不需要标记任何方法,因为类中的方法通常可以修改类属性(类的性质)
“Use extension to add functionality to an existing type, such as new methods and computed properties. You can use an extension to add protocol conformance to a type that is declared elsewhere, or even to a type that you imported from a library or framework”
使用 extension 来为现有的类型添加功能,比如新的方法和计算属性。你可以使用扩展在别处修改定义,甚至是从外部库或者框架引入的一个类型,使得这个类型遵循某个协议
摘录来自: Apple Inc. “The Swift Programming Language (Swift 3)”。 iBooks P43.
defer
“Use defer to write a block of code that is executed after all other code in the function, just before the function returns. The code is executed regardless of whether the function throws an error. You can use defer to write setup and cleanup code next to each other, even though they need to be executed at different times”
defer是swift2.0推出的语法,用于在code最后执行一些清理工作,如文件读取操作,在最后关闭文件,就可以放在defer中。
摘录来自: Apple Inc. “The Swift Programming Language (Swift 3)”。 iBooks P48.
整形浮点型转化
“let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double”
注意类型转换的方法是Double(three)而不是(Double)three,我的理解是有一个内置构造器用来生成一个新值。
摘录来自: Apple Inc. “The Swift Programming Language (Swift 3)”。 iBooks P76.
一些关键词
- final //防止重写,如果修饰class,将不能继承
- convenience //便利构造器
- required //表明所有该类的子类都必须实现该构造器
- unowned //无主引用
- AnyObject //可以代表任何class类型的实例
- Any //可以表示任何类型,包括方法类型(function types)。