经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Swift » 查看文章
Swift4 类和结构体,例子代码。
来源:cnblogs  作者:youv  时间:2018/9/25 20:29:14  对本文有异议

类和结构体

苹果官方文档 Classes and Structures

苹果官方文档翻译 类和结构体

类与结构体的对比

定义语法

  1. class SomeClass {
  2. // class definition goes here
  3. }
  4. struct SomeStructure {
  5. // structure definition goes here
  6. }

一个实际的代码例子如下:

  1. struct Resolution {
  2. var width = 0
  3. var height = 0
  4. }
  5. class VideoMode {
  6. var resolution = Resolution()
  7. var interlaced
  8. }

类与结构体实例

  1. let someResolution = Resolution()
  2. let someVideoMode = VideoMode()

访问属性

  1. print("The width of someResolution is \(someResolution.width)")
  2. // prints "The width of someResolution is 0"
  3. print("The width of someVideoMode is \(someVideoMode.resolution.width)")
  4. // prints "The width of someVideoMode is 0"
  5. someVideoMode.resolution.width = 1280
  6. print("The width of someVideoMode is now \(someVideoMode.resolution.width)")

结构体类型的成员初始化器

  1. let vga = Resolution(width: 640, height: 480)

但是,类实例不会接收默认的成员初始化器。

结构体和枚举是值类型

值类型是一种当它被指定到常量或者变量,或者被传递给函数时会被拷贝的类型。

  1. let hd = Resolution(width: 1920, height: 1080)
  2. var cinema = hd
  3. cinema.width = 2048
  4. println("cinema is now \(cinema.width) pixels wide")
  5. //println "cinema is now 2048 pixels wide"
  6. print("hd is still \(hd.width) pixels wide")
  7. // prints "hd is still 1920 pixels wide"
  1. enum CompassPoint {
  2. case North, South, East, West
  3. }
  4. var currentDirection = CompassPoint.West
  5. let rememberedDirection = currentDirection
  6. currentDirection = .East
  7. if rememberedDirection == .West {
  8. print("The remembered direction is still .West")
  9. }
  10. // prints "The remembered direction is still .West"

类是引用类型

  1. let tenEighty = VideoMode()
  2. tenEighty.resolution = hd
  3. tenEighty.interlaced = true
  4. tenEighty.name = "1080i"
  5. tenEighty.frameRate = 25.0
  6. let alsoTenEighty = tenEighty
  7. alsoTenEighty.frameRate = 30.0
  8. print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
  9. // prints "The frameRate property of tenEighty is now 30.0"

特征运算符

找出两个常量或者变量是否引用自同一个类实例非常有用,为了允许这样,Swift提供了两个特点运算符:

  1. 相同于 ( ===)
  2. 不相同于( !==)
  1. if tenEighty === alsoTenEighty {
  2. print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
  3. }
  4. // prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."

类和结构体之间的选择

字符串,数组和字典的赋值与拷贝行为

详见文档原文

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号