从oc向swift过渡并不是向很多人说的那么简单。swift3.0的感觉就是让我们用更少的代码,更规范的格式进行开发。过渡期间还是有很多东西需要去改变。这篇文章主要讲Classes 和 structures。Classes和structures最重要的区别的是Classes 是引用类型,而structures则是值类型。关于引用类型和值类型,将在后面机型讲解。
在官方文档中,struct和class 放在一起。接下来就讲讲他们的异同吧。
官方地址class和struct英文官方地址,中文翻译地址:class和struct中文地址。
class和struct的相同点:
Classes and structures in Swift have many things in common. Both can:
1.Define properties to store values 定义属性用于存储。
2.Define methods to provide functionality 定义方法 function。
3.Define subscripts to provide access to their values using subscript syntax 定义下标操作使得可以通过下标语法来访问实例所包含的值。
4.Define initializers to set up their initial state定义构造器进行初始化。
5.Be extended to expand their functionality beyond a default implementation可以扩展function
6.Conform to protocols to provide standard functionality of a certain kind实现协议。
讲讲差异点(Classes have additional capabilities that structures do not):
1.Inheritance enables one class to inherit the characteristics of another.c;可以进行继承。
2.Type casting enables you to check and interpret the type of a class instance at runtime.在编译的时候可以进行类型检查和解释类实例
3.Deinitializers enable an instance of a class to free up any resources it has assigned.类实例可以释放其所占有的资源。
4.Reference counting allows more than one reference to a class instance.允许实例多次引用。
接下来讲解一些使用概念:
Note1.在每次定义一个新类或者结构体的时候,实际上你是定义了一个新的 Swift 类型。比如classA 或者structB是一个新的类型,只不过这是自定义类型。
Note2.结构在传递的时候,其值会被拷贝。比如structB=structA,只是简单的值传递。structB的操作不会影响structA。而类则是引用类型,classB=classA。classB的操作会影响到classA。所以class传递的实例本身,而不是简单的值复制。
class和struct的选择:
1.该数据结构的主要目的是用来封装少量相关简单数据值,比如基础数据类型。
2.有理由预计该数据结构的实例在被赋值或传递时,封装的数据将会被拷贝而不是被引用。
3.该数据结构中储存的值类型属性,也应该被拷贝,而不是被引用。
4.该数据结构不需要去继承另一个既有类型的属性或者行为。
网友评论