定义语法
class SomeClass {
// class definition goes here
}
struct SomeStructure {
// structure definition goes here
}
//eg
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)")
// 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)")
// prints "The width of someVideoMode is now 1280"
结构体类型的成员初始化器
let vga = Resolution(width: 640, height: 480)
结构体和枚举是值类型
//Swift 中所有的结构体和枚举都是值类型
//这意味着你所创建的任何结构体和枚举实例——和实例作为属性所包含的任意值类型——在代码传递中总是被拷贝的
//结构体eg:
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"
//枚举eg:
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"
特征运算符
===: 意味着两个类类型常量或者变量引用自相同的实例
!==:
==: 意味着两个实例的在值上被视作“相等”或者“等价”,某种意义上的“相等”,就如同类设计者定义的那样
!=:
指针
//如果你有过 C,C++ 或者 Objective-C 的经验,你可能知道这些语言使用可指针来引用内存中的地址。
//一个 Swift 的常量或者变量指向某个实例的引用类型和 C 中的指针类似,但是这并不是直接指向内存地址的指针,也不需要你书写星号( *)来明确你建立了一个引用。
//相反,这些引用被定义得就像 Swift 中其他常量或者变量一样。
字符串,数组和字典的赋值与拷贝行为 (值类型)
//Swift 的 String , Array 和 Dictionary类型是作为结构体来实现的,这意味着字符串,数组和字典在它们被赋值到一个新的常量或者变量
//亦或者它们本身被传递到一个函数或方法中的时候,其实是传递了拷贝。