Swift做爲現代語言,面向對象編程是必須支持的。html
class Person{ var name: String = "" var age: Int = 0 init(name:String,age:Int){ self.name = name self.age = age } deinit { // 執行析構過程 } } let p1 = Person(name: "張三", age: 25) print(p1.name)
init是類的構造函數,deinit爲析構函數
Swift 會使用引用計數自動釋放再也不須要的實例以釋放資源。
可是有時候須要在deinit中執行一些釋放代碼,好比關閉文件。ios
class Site{ var domain = "" init(domain:String){ self.domain = domain } var url: String{ get{ return "http://"+domain; } set{ var url = newValue let range = Range<String.Index>(start: url.startIndex,end: advance(url.startIndex, 7)) url.removeRange(range) self.domain = url } } } let s1 = Site(domain: "www.aswifter.com") print(s1.url) s1.url = "http://www.baidu.com" print(s1.domain)
set方法中的newValue是默認預設的變量,表明將要設置的值,
newValue是常量,不能改變git
class Counter { var count = 0 func increment() { count++ } func incrementBy(amount: Int) { count += amount } func reset() { count = 0 } } let counter = Counter() // 初始計數值是0 counter.increment() // 計數值如今是1 counter.incrementBy(5) // 計數值如今是6 counter.reset() // 計數值如今是0
class Hello{ class func sayHello(name: String){ print("hello " + name) } } Hello.sayHello("陽春麪")
subscript有點像‘[]’這個符號的運算符重載。編程
class TimesTable { var multiplier: Int = 0 init(multiplier: Int){ self.multiplier = multiplier } subscript(index: Int) -> Int { return multiplier * index } } let threeTimesTable = TimesTable(multiplier: 3) print("3的6倍是\(threeTimesTable[6])")
經過threeTimesTable[6]這樣的下標調用,訪問subscript定義的方法。swift
class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at \(currentSpeed) miles per hour" } func makeNoise() { } } class Train: Vehicle { var hasBasket = false override func makeNoise() { print("Choo Choo") } } let train = Train() train.makeNoise()
繼承的寫法與C++相同,使用override關鍵字重寫方法;
若是一個方法不想被重寫,能夠在override加final關鍵字微信
使用is判斷類型,使用as轉換類型app
let vehicles = [ Vehicle(), Train() ] var trainCount = 0 for item in vehicles{ if item is Train{ ++trainCount } if let train = item as? Train{ train.makeNoise() } } print("trainCount=\(trainCount)")
class Outer{ class Inner{ func hello() -> String{ return "hello" } } } let inner = Outer.Inner() print(inner.hello())
The Swift Programming Language 中文版
The Swift Programming Language 2.0 官方教程dom
本文做者: 陽春麪
原文地址:http://www.aswifter.com/2015/07/21/learn-swift-with-playground-class/ide
歡迎關注個人微信公衆號,分享Android 開發,IOS開發,Swift開發和互聯網內容
微信號:APP開發者
函數