发布于 2017-05-25 10:43:37 | 129 次阅读 | 评论: 0 | 来源: 网友投递
Swift编程语言
SWIFT,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C*共同运行于Mac OS和iOS平台,用于搭建基于苹果平台的应用程序。
前言
和其他语言不同的是,Swift不需要为自定义的类和结构体创建接口和实现文件。只需要创建单一文件用来创建类和结构体,其他的外部接口的代码系统会自动生成。下面这篇文章主要介绍了关于Swift 3.0类与结构体的内容,感兴趣的朋友一起来看看吧。
类和结构体区别
Swift的类和结构体具有以下相同的特点:
类具有结构体没有的额外的功能:
结构体一般来说赋值的时候是直接拷贝的,没有使用引用计数的机制。
符号定义
下面是一个定义结构体和类的例子:
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
结构体初始化的时候可以直接
let vga = Resolution(width: 640, height: 480)
这点和类不一样,类没有默认的逐个成员的初始化器。
结构体和枚举是值类型
let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
再赋值
cinema.width = 2048
结果
print("cinema is now \(cinema.width) pixels wide")
// Prints "cinema is now 2048 pixels wide"
然而hd.width还是1920
print("hd is still \(hd.width) pixels wide")
// Prints "hd is still 1920 pixels wide"
可见赋值过程是做了一次深度拷贝。
枚举也是具有同样的行为, 如以下例子,rememberedDirection的值并没有改变:
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")
}
// Prints "The remembered direction is still .west"
类是引用类型
例如:
let tenEighty = VideoMode()
tenEighty.resolution = hd
tenEighty.interlaced = true
tenEighty.name = "1080i"
tenEighty.frameRate = 25.0
进行赋值引用
let alsoTenEighty = tenEighty
alsoTenEighty.frameRate = 30.0
结果
print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
// Prints "The frameRate property of tenEighty is now 30.0"
标识符
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
}
// Prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."
完全相同(===)和等于(==)是不一样的:
选择使用类和结构体
由于结构体的实例一般是值传递,而类实例一般是引用传递,因此你需要根据实际情况来考虑应该定义一个类还是结构体.
如有以下一种或多仲情况使用结构体:
看看几个使用结构体恰当的例子:
其他的情况请定义类并创建类实例,管理和传递都使用引用。
在实践中,大部分的自定义数据结构都是使用类居多,很少使用结构体。
String、Array和Dictionary的赋值和拷贝行为
String, Array和 Dictionary都是结构体,因此赋值直接是拷贝,而NSString, NSArray 和NSDictionary则是类,所以是使用引用的方式。
参考英语原文:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-ID82
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对PHPERZ的支持。