当前位置: 首页 > 编程学习 > 其它语言 > Swift > 正文

Swift4 类和结构体,例子代码

2018-04-22 来源:博客园/CC_Joy

类和结构体

苹果官方文档 Classes and Structures

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

类与结构体的对比

定义语法

  class SomeClass {
      // class definition goes here
  }  
  struct SomeStructure {
      // structure definition goes here
  }

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

struct Resolution {
    var width = 0
    var height = 0
}
class VideoMode {
    var resolution = Resolution()
    var interlaced
}

类与结构体实例

let someResolution = Resolution()
let someVideoMode = VideoMode()

访问属性

print("The width of someResolution is \(someResolution.width)")
// prints "The width of someResolution is 0"
 
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
// prints "The width of someVideoMode is 0"
 
someVideoMode.resolution.width = 1280
print("The width of someVideoMode is now \(someVideoMode.resolution.width)")

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

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

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

结构体和枚举是值类型

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

let hd = Resolution(width: 1920, height: 1080)
var cinema = hd
cinema.width = 2048
println("cinema is now \(cinema.width) pixels wide")
//println "cinema is now 2048 pixels wide"
print("hd is still \(hd.width) pixels wide")
// prints "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")
}
// 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"

特征运算符

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

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

类和结构体之间的选择

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

详见文档原文