Swift教程-类与结构体

来源:互联网 发布:mac下视频音频格式转换 编辑:程序博客网 时间:2024/09/21 09:01

swift 中类于结构体

swift中结构体与类既相似,又有不同。

相似点
- 可以保存变量
- 保存函数

不同点
- 结构体不支持继承,类支持
- 结构体是引用类型,类引用类型

.

  1. 定义
// 结构体定义struct SomeStructure {    //成员变量    var width = 0    var height = 0}// 类定义class SomeClass {    //成员变量    var resolution = Resolution()    var interlaced = false    var frameRate = 0.0    var name: String?}

2.实例化变量

let someResolution = Resolution()let someVideoMode = VideoMode()//带参数的初始函数let vga = Resolution(width: 640, height: 480)

3.结构体是值变量

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

4.类是引用变量
类是类似于C指针一样的引用变量

let tenEighty = VideoMode()tenEighty.frameRate = 25.0let alsoTenEighty = tenEightyalsoTenEighty.frameRate = 30.0// Prints "The frameRate property of tenEighty is now 30.0"print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")

5.Swift基本数据类型内的结构体与Foundation内的类

在swift中的数据类型均为结构体,如String,Array,Dictionary。即在赋值传递中均为值传递
在Foundation库中,NSString,NSArry,NSDictionary都是用类实现,在传递的过程中为引用传递

0 0
原创粉丝点击