Swift4 基础部分: Classes and Structures

本文是学习《The Swift Programming Language》整理的相关随笔,基本的语法不作介绍,主要介绍Swift中的一些特性或者与OC差异点。

系列文章:

比较类与结构体(Comparing Classes and Structures)

Classes and structures in Swift have many things in common. Both can:

- Define properties to store values
- Define methods to provide functionality
- Define subscripts to provide access to their values using subscript syntax
- Define initializers to set up their initial state
- Be extended to expand their functionality beyond a default implementation
- Conform to protocols to provide standard functionality of a certain kind
- 
For more information, see Properties, Methods, Subscripts, Initialization, Extensions, and Protocols.

Classes have additional capabilities that structures do not:

- Inheritance enables one class to inherit the characteristics of another.
- Type casting enables you to check and interpret the type of a class instance at runtime.
- Deinitializers enable an instance of a class to free up any resources it has assigned.
- Reference counting allows more than one reference to a class instances

Swift 中类和结构体有很多共同点。共同处在于:

  • 定义属性用于存储值
  • 定义方法用于提供功能
  • 定义附属脚本用于访问值
  • 定义构造器用于生成初始化值
  • 通过扩展以增加默认实现的功能
  • 符合协议以对某类提供标准功能

与结构体相比,类还有如下的附加功能:

  • 继承允许一个类继承另一个类的特征
  • 类型转换允许在运行时检查和解释一个类实例的类型
  • 解构器允许一个类实例释放任何其所被分配的资源
  • 引用计数允许对一个类的多次引用

定义语法(Definition Syntax)

Classes and structures have a similar definition syntax. 
You introduce classes with the class keyword and 
structures with the struct keyword. 

例子:

struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

var someResolution = Resolution();
someResolution.width = 10;
someResolution.height = 10;
var someVideoMode = VideoMode();
someVideoMode.resolution = someResolution;
someVideoMode.frameRate = 1.0;
someVideoMode.name = "mp4";

print("someVideoMode.resolution: (\(someVideoMode.resolution.width) \(someVideoMode.resolution.height)),someVideoMode.name \(someVideoMode.name)");

执行结果:

someVideoMode.resolution: (10 10),someVideoMode.name Optional("mp4")

结构体与枚举都是值类型数据(Structures and Enumerations Are Value Types)

A value type is a type whose value is copied when it is 
assigned to a variable or constant, or when it is passed 
to a function.

结构体例子:

struct Resolution {
    var width = 0
    var height = 0
}

let hd = Resolution(width:1920,height:1080)
var cinema = hd
cinema.width = 2048
print("cinema is now \(cinema.width) pixels wide")
print("hd is still \(hd.width) pixels wide")

执行结果:

cinema is now 2048 pixels wide
hd is still 1920 pixels wide

枚举例子:

enum CompassPoint {
    case north, south, east, west
}
var currentDirection = CompassPoint.west
let rememberedDirection = currentDirection
currentDirection = .east
if rememberedDirection == .west {
    print("The remembered direction is still .west")
}

执行结果:

The remembered direction is still .west

类是引用类型数据(Classes Are Reference Types)

Unlike value types, reference types are not copied when 
they are assigned to a variable or constant, or when they 
are passed to a function. Rather than a copy, a reference 
to the same existing instance is used instead.

例子:

struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

var someVideoMode = VideoMode();
someVideoMode.name = "mp4";

var otherVideoMode = someVideoMode;
otherVideoMode.name = "AVI"
print("someVideoMode.name : (\(someVideoMode.name)");

执行结果:

someVideoMode.name : (Optional("AVI")

恒等式操作符(Identity Operators)

It can sometimes be useful to find out if two constants or 
variables refer to exactly the same instance of a class. 
To enable this, Swift provides two identity operators:

Identical to (===)

Not identical to (!==)

接着上述的例子:

struct Resolution {
    var width = 0
    var height = 0
}

class VideoMode {
    var resolution = Resolution()
    var interlaced = false
    var frameRate = 0.0
    var name: String?
}

var someVideoMode = VideoMode();
someVideoMode.name = "mp4";

var otherVideoMode = someVideoMode;
otherVideoMode.name = "AVI"

var thirdVideoMode = VideoMode();

if someVideoMode === otherVideoMode{
    print("someVideoMode === otherVideoMode")
}

if someVideoMode !== thirdVideoMode{
    print("someVideoMode !== thirdVideoMode")
}

执行结果:

someVideoMode === otherVideoMode
someVideoMode !== thirdVideoMode

类和结构体的选择(Choosing Between Classes and Structures)

You can use both classes and structures to define custom data types to use as the building blocks of your program’s 
code.

However, structure instances are always passed by value, 
and class instances are always passed by reference. This 
means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that 
you need for a project, decide whether each data construct 
should be defined as a class or as a structure.

As a general guideline, consider creating a structure when 
one or more of these conditions apply:

- The structure’s primary purpose is to encapsulate a few 
relatively simple data values.

- It is reasonable to expect that the encapsulated values 
will be copied rather than referenced when you assign or 
pass around an instance of that structure.

- Any properties stored by the structure are themselves 
value types, which would also be expected to be copied rather than referenced.

- The structure does not need to inherit properties or behavior from another existing type.

Examples of good candidates for structures include:

- The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.

- A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.

- A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.


In all other cases, define a class, and create instances 
of that class to be managed and passed by reference. In 
practice, this means that most custom data constructs 
should be classes, not structures.

按照通用的准则,当符合一条或多条以下条件时,请考虑构建结构体:

  • 结构体的主要目的是用来封装少量相关简单数据值。
  • 有理由预计一个结构体实例在赋值或传递时,封装的数据将会被拷贝而不是被引用。
  • 任何在结构体中储存的值类型属性,也将会被拷贝,而不是被引用。
  • 结构体不需要去继承另一个已存在类型的属性或者行为。

合适的结构体候选者包括:

  • 几何形状的大小,封装一个width属性和height属性,两者均为Double类型。
  • 一定范围内的路径,封装一个start属性和length属性,两者均为Int类型。
  • 三维坐标系内一点,封装x,y和z属性,三者均为Double类型。

字符串与集合类型的赋值和拷贝行为(Assignment and Copy Behavior for Strings, Arrays,and Dictionaries)

In Swift, many basic data types such as String, Array, and 
Dictionary are implemented as structures. This means that 
data such as strings, arrays, and dictionaries are copied 
when they are assigned to a new constant or variable, or 
when they are passed to a function or method.
  • 在Swift中String,Array,Dictionary都是以结构体的方式实现的。因此当使用它们赋值或者传入函数作为参数时都是以拷贝的方式传入。

例子:

var array:[Int] = [1,2,3]
var otherArray = array
otherArray.append(4)
print("array:\(array),otherArray:\(otherArray)")

执行结果:

array:[1, 2, 3],otherArray:[1, 2, 3, 4]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,165评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,720评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,849评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,245评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,596评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,747评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,977评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,708评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,448评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,657评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,141评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,493评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,153评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,108评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,890评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,799评论 2 277
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,685评论 2 272

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,623评论 4 59
  • 常量与变量使用let来声明常量,使用var来声明变量。声明的同时赋值的话,编译器会自动推断类型。值永远不会被隐式转...
    莫_名阅读 393评论 0 1
  • 简单搭建监控系统 基础环境: 安装k2-compose 下载监控系统部署模版另存为k2-compose.yml,或...
    rm_rf阅读 742评论 0 1
  • I:在表达称赞时,如果能先描述所称赞的具体内容,并且加上对方的称谓或类似独有信息的话,能让对方感到获得了特别的关注...
    幸福虚度的野人阅读 236评论 0 2
  • 12月29日-12月30日 下面这段话是一位圈柚在圈圈三问中的提问,请你帮她梳理思路,概括出ta所表达的主题,来更...
    孙悟饭Y阅读 223评论 0 1