swift类和结构体(一)

An instance of a class is traditionally known as an object. However, Swift classes and structures are much closer in functionality than in other languages, and much of this chapter describes functionality that can apply to instances of either a class or a structure type. Because of this, the more general term instance is used.
通常一个类的实例被称为对象。然而,swift中类和结构体比其他任何一门语言都要接近。本章节描述的许多功能都可以应用在类和结构体上。因此,大多数属于上我们应用实例。
结构体和类的异同
相同点:
1.定义属性用于存储值。
2.定义函数以提供功能
3.定义下标,以便用下标语法来访问它们的值。
4.定义初始化程序,以创建它们的厨师状态。
5.通过扩展来扩展它们的默认实现。
6.利用协议来完成特定标准功能。
和结构体相比,类还有结构体不具有的附加功能:
1.继承使类一个类继承另一个类的特性。
2.类型转换允许你在运行时,检查和解释一个类实例的类型。
3.取消初始化器,允许一类的实例释放它所占有的资源。
4.计数器允许对一个实例进行多次引用。
这里写图片描述
注意
结构体在您的代码中传递的时候不是进行的引用,而总是被拷贝。
定义
swift类和结构体(一)_第1张图片
注意
swift类和结构体(一)_第2张图片
定义类和结构体的命名,都要用首字母为大写的驼峰命名法。相反,命名属性和方法要要用矮驼峰来和类型进行区分。
类和结构体的实例
swift类和结构体(一)_第3张图片
类和结构体的实例比较简单,只需要在类名后边加上一对括号即可。实例的属性值就是默认值,实例的更多初始化细节在Initialization方法里边。
属性访问
swift的属性比较简单,直接设置即可。
结构体类型的初始化器
All structures have an automatically-generated memberwise initializer, which you can use to initialize the member properties of new structure instances. Initial values for the properties of the new instance can be passed to the memberwise initializer by name:
所有的结构体都有一个自动生成的初始化器,它可以用来初始化新结构体的属性。为实例的初始化值,可以通过名字传递到初始化器中。
swift类和结构体(一)_第4张图片
Unlike structures, class instances do not receive a default memberwise initializer. Initializers are described in more detail in Initialization.
不像结构体,类没有这种默认的初始化器。

你可能感兴趣的:(swift)