结构体和类的声明 以及实例化
import UIKit
// 结构体和类的声明
struct Resolution {
var width = 0
var height = 0
}
class VideoMode {
var resolution = Resolution()
var interlaced = false
var frameRate = 0.0
var name: String?
}
// 结构体和类的实例化
let someResolution = Resolution()
let someVideoMode = VideoMode()
属性的访问
// 访问属性
print("The width of someResolution is \(someResolution.width)")
print("The width of someVideMode is \(someVideoMode.resolution.width)")
someVideoMode.resolution.width = 1280
print("The width of someVideMode is now \(someVideoMode.resolution.width)")
console log 如下
结构体是值拷贝
// 结构体是值拷贝
let vga = Resolution(width: 640, height: 480)
var cinema = vga
cinema.height = 960
print("cinema is now \(cinema.height) pixels height")
print("vga is still \(vga.height) pixels height")
console log 如下
枚举也是值拷贝
// 枚举也是值拷贝
enum CompassPoint {
case notth, south, east, west
}
var currentDirection = CompassPoint.west
let rememberedDirection = currentDirection
currentDirection = .east
if rememberedDirection == .west {
print("The remembered direction is still .west")
}
console log 如下
类是引用类型
// 类是引用类型
let tenEighty = VideoMode()
tenEighty.resolution = vga
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)")
console log 如下
=== 或者 !== 运算符
// === 运算符 或者 !==
if tenEighty === alsoTenEighty {
print("tenEighty and alsoTenEighty refre to the same VideoMode instance")
}
console log 如下
注意:在Swift 中String,Array,Dictionary 都是作为结构体实现的,也就是在赋值时以及作为函数参数时都是进行的值拷贝