/*************** 初始化 *******************/
// 在使用 實(shí)類,結(jié)構(gòu)體,枚舉之前都需要初始化
// 初始化過程需要給 存儲屬性設(shè)值, 并做其他初始化操作.
// 和oc 不同, swift 初始化并不反回值.
// 初始化是為了確保這個實(shí)類在第一次使用的前已經(jīng)做好了準(zhǔn)備
// 初始化給存儲屬性設(shè)值
// 類和結(jié)構(gòu)體在初始化時必須給所有存儲屬性賦值. 存儲屬性不允許有不確定值得狀態(tài)
// 也可以在定義存儲屬性時給它設(shè)一個默認(rèn)值, 該操作不會觸發(fā)觀察者模式
struct Fahrenheit{
var temperature: Double
init(){
temperature = 32.0// 初始化設(shè)置默認(rèn)值
}
}
var f = Fahrenheit()
print("The default temperature is \(f.temperature)")
//Prints "The default temperature is 32.0 Fahrenheit"
// 設(shè)置存儲屬性默認(rèn)值
// 屬性申明的時候就設(shè)置默認(rèn)值
struct FahrenheitA{
var temperature = 32.0
}
// 建議多使用申明默認(rèn)值 而不是 初始化設(shè)置默認(rèn)值
//---------自定義初始化-----
struct Celsius{
var temperatureinCelsius:Double
init(fromFahrenheit fahrenheit: Double){
temperatureinCelsius = (fahrenheit - 32.0)/1.8
}
init(fromKelvin kelvin:Double){
temperatureinCelsius = kelvin - 273.15
}
}
let boilingPointOfWater = Celsius(fromFahrenheit: 212.0)
// boi9lingPointOfWater.temperatureInCelsius is 100.0
let freezingPointOfWater = Celsius(fromKelvin: 273.15)
// freezingPointOfWater.temperatureInCelsius is 0.0
//-----------參數(shù)名 和參數(shù)標(biāo)簽-------
// 在初始化中, 默認(rèn) 參數(shù)名就是標(biāo)簽名, 方法內(nèi)部和外部都可以用
struct Color{
let red, green, blue: Double
init(red: Double, green: Double, blue: Double){
self.red = red
self.green = green
self.blue = blue
}
init(white: Double){
red = white
green = white
blue = white
}
}
let magenta = Color(red: 1.0, green:0.0, blue: 1.0)
let halfGray = Color(white: 0.5)
//let veryGreen = Color(0.0, 1.0, 0.0)
// 報錯, Missing argument labels 'red:green:blue:' in call
// 那么如何在初始化的時候 不顯示參數(shù)名呢?
// 定義初始化方法時 ,用下劃線 代表表情參數(shù)就可
struct CelsiusA {
var temperatureInCelsius: Double
init(fromFahrenheit fahrenheit: Double) {
temperatureInCelsius = (fahrenheit - 32.0) / 1.8
}
init(fromKelvin kelvin: Double) {
temperatureInCelsius = kelvin - 273.15
}
init(_ celsius: Double) {
temperatureInCelsius = celsius
}
}
let bodyTemperature = CelsiusA(37.0)
// bodyTemperature.temperatureInCelsius is 37.0
// --------可選屬性值---------
// 變量名:數(shù)據(jù)類型?
// 可選屬性 在初始化時可以為 nil
class SurveyQuestion{
var text: String
var response: String?
init(text:String){
self.text = text
}
func ask(){
print(text)
}
}
let cheeseQuestion = SurveyQuestion(text: "Do you like cheese?")
cheeseQuestion.ask()
//Prints "Do you like cheese?"
cheeseQuestion.response = "Yes, I do like cheese"
//---------- 初始化時 使用 靜態(tài)常量屬性 ---------
// 初始化時可以更改常量屬性的值?
class SurveyQuestionA{
let text: String
var response:String?
init(text: String) {
self.text = text
}
func ask(){
print(text)
}
}
let beetsQuestion = SurveyQuestionA(text: "How about beets")
beetsQuestion.response = "I alse like beets. (But not with cheese)"
// 在初始化之前 text 的值為空, 初始化時 我們給一個 常量值賦值了
//--------- 默認(rèn)的初始化方法----------
// swift 為 類和結(jié)構(gòu)體提供了默認(rèn)的初始化方法
// 這時候 屬性都需要設(shè)置默認(rèn)值.
class ShoppingListItem:NSObject{
var name: String? //默認(rèn)值 是 nil
var quantity = 1
var purchased = false
}
var item = ShoppingListItem()
//------- 結(jié)構(gòu)體類型的逐個初始化---------
//如果結(jié)構(gòu)體沒有自定義初始化方法
// 結(jié)構(gòu)體可以逐個給屬性賦值的方法初始化
struct Size{
var width = 0.0, height = 0.0
}
let twoByTwo = Size(width: 2.0, height: 2.0)
//---------- 值類型 的多個初始化方法委托調(diào)用 -------
// 值類型的 初始化委托調(diào)用比較簡單, 直接在需要的地方 調(diào)用 self.init 就可
// 類 類型 是可以繼承的, 所有他的委托調(diào)用畢竟復(fù)雜
// 也可以把 委托調(diào)用的 初始化方法 寫到 擴(kuò)展 Extension 中 (后面Extension 內(nèi)容 中 會提到)
struct SizeA{
var width = 0.0, height = 0.0
}
struct Point{
var x = 0.0, y = 0.0
}
struct Rect{
var origin = Point()
var size = SizeA()
init(){}
init(origin: Point, size: SizeA){
self.origin = origin
self.size = size
}
init(center: Point, size: SizeA){
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
// 委托調(diào)用
self.init(origin: Point(x: originX, y: originY), size: size)
}
}
let basicRect = Rect()
// basicRect 的 origin 是 (0.0, 0.0) size is (0.0, 0.0)
let originRect = Rect(origin: Point(x: 2.0, y:2.0), size: SizeA(width: 5.0, height:5.0))
// originRect 的 origin = (2.0, 2.0) size = (5.0, 5.0)
let centerRect = Rect(center: Point(x: 4.0, y:4.0), size: SizeA(width: 3.0, height: 3.0))
// centerRect's origin = (2.5, 2.5) size = (3.0, 3.0)
// ---------------類 繼承 和 初始化 ----------
// 類的所有存儲屬性, 包括從父類哪里繼承來的屬性,在初始時都要一個初始值
// swfit 有兩種方法給存儲屬性設(shè)置設(shè)置初始值.
// 1. 指定初始化
// 2. 便捷初始化
// -----------指定初始化 和 便捷 初始化 --------
//http://swifter.tips/init-keywords/
// Designated 指定初始化時最常用,最主要的初始化方法, 初始化過程中 會給所有存儲屬性一個初始化值
// 任何類至少有一個 Designated 指定初始化方法
//
// Convenience 便捷初始化是二等初始化方法
// 他必須在內(nèi)部調(diào)用一個 Designated 指定初始化方法.
// 可以給一些屬性設(shè)置默認(rèn)值,可以給一些屬性設(shè)置初始值
// 便捷初始化 可有可無
//
// 指定初始化
//init(parameters){
// statements
//}
// 便捷初始化
// convenience init(parameters){
// statements
//}
// ---------- 類 的初始化 委托------------
// 3 個準(zhǔn)則
// 1. Designated 初始化方法 必須調(diào)用一個自己直接父類的 Designated 初始化方法
// 2. Convenience 初始化 方法 必須調(diào)用另外一個 該類的初始化方法(Convenience 或者 Designated)
// 3. Convenience 最終還是要調(diào)用一個 Designated 初始化方法
// designate 可以向上調(diào)用父類的designate
// Conveninece 只能調(diào)用該類的 初始化方法.
//---------- 類 初始化的兩個階段----------------
// 第一階段, 給所有存儲屬性一個初始值
// 第二階段, 在類初始化為實(shí)類之前對初始值進(jìn)行改造
// 和 oc 初始化不同, oc 初始化時, 所有的屬性都是 nil
// 初始化 編譯的過程的四個安全檢查
// 1. 在調(diào)用父類初始化之前 必須給子類特有的屬性設(shè)置初始值, 只有在類的所有存儲屬性狀態(tài)都明確后, 這個對象才能被初始化
// 2. 先調(diào)用父類的初始化方法, 再 給從父類那繼承來的屬性初始化值, 不然這些屬性值 會被父類的初始化方法覆蓋
// 3. convenience 必須先調(diào)用 designated 初始化方法, 再 給屬性初始值. 不然設(shè)置的屬性初始值會被 designated 初始化方法覆蓋
// 4. 在第一階段完成之前, 不能調(diào)用實(shí)類方法, 不能讀取屬性值, 不能引用self
// 第一階段:
// - designated 或者 convenience 初始化方法被調(diào)用
// - 實(shí)類的內(nèi)存被分配, 這時內(nèi)存還沒有完全被初始化
// - 類的 designated 初始化方法確保所有的存儲屬性有了初始值, 保存這些存儲屬性的內(nèi)存被初始化
// - 初始化方法傳遞給父類, 由父類完成上面的過程, 存儲所有存儲屬性值
// - 繼續(xù)向繼承鏈的上部傳遞,直到最頂層
// - 一直到最頂層的類的所有存儲屬性都被設(shè)置了初始值, 說明這個類的內(nèi)存初四哈哈完成. 整個初始化的第一階段結(jié)束
// 第二階段
// - 從繼承鏈頂部到底部, 每個 designated 初始化方法都可以 引用 self, 修改屬性值, 調(diào)用實(shí)類方法.等
// - 最后 任何 convenience 初始化方法中都可以 定制實(shí)類, 引用 self
// --------------- 初始化的繼承和重寫 ------------
//http://www.cnblogs.com/Rinpe/p/5189111.html
/*
構(gòu)造器的繼承:
Swift的子類不會自動繼承父類的構(gòu)造器, 若繼承, 則滿足如下規(guī)則:
1.如果子類沒有提供任何指定構(gòu)造器, 那么它將自動繼承父類的所有指定構(gòu)造器
2.如果子類實(shí)現(xiàn)了父類所有的指定構(gòu)造器, 無論如何實(shí)現(xiàn)的, 都將自動繼承父類的所有便利構(gòu)造器
*/
/*
構(gòu)造器的重寫:
1.子類構(gòu)造器重寫了父類的指定構(gòu)造器, 必須添加override修飾符
2.子類中定義的構(gòu)造器只是和父類中便利構(gòu)造器的形參列表, 外部形參名相同, 不算重寫
*/
/*
總結(jié):
1.如果一個子類沒有定義任何構(gòu)造器, 那么它將自動繼承父類中的所有構(gòu)造器
2.如果一個子類重寫父類的所有指定構(gòu)造器, 那么它將自動繼承父類中的所有便利構(gòu)造器
3.如果一個子類中任意的構(gòu)造器和父類的便利構(gòu)造器一模一樣, 不算重寫, 創(chuàng)建對象的時候也只會顯示子類定義的構(gòu)造器
*/
// 注意: 即使你重寫的是父類的 designated 構(gòu)造器, 子類也可以寫作 convenience 構(gòu)造器, 即: designated 可以重寫為 convenience
// convenience 構(gòu)造器 不能被重寫
class Vehicle{
var numberOfWheels = 0
var description: String {
return "\(numberOfWheels) wheels"
}
}
let vehicle = Vehicle()
print("Vehicle: \(vehicle.description)")
//Vehicle: 0 wheels
class Bicycle: Vehicle{
override init() {
super.init()
numberOfWheels = 2
}
}
let bicycle = Bicycle()
print("Bicycle: \(bicycle.description)")
//Bicycle: 2 wheels
// 子類可以修改 繼承來的變量屬性, 不能修改常量屬性
//-----------構(gòu)造器自定繼承----------
// swift 默認(rèn)不繼承 構(gòu)造器
// 當(dāng)子類 1 個構(gòu)造器也沒有時, 會自動繼承父類所有的構(gòu)造器
// 規(guī)則1: 當(dāng)子類沒有定義任何構(gòu)造器, 子類自動繼承父類所有designated 構(gòu)造器
// 規(guī)則2: 當(dāng)子類實(shí)現(xiàn)了父類所有的designated 構(gòu)造器方法,無論是像規(guī)則1那樣從父類繼承的,還是自定義實(shí)現(xiàn)的, 都會自動繼承父類所有的 convenience 構(gòu)造器
// 關(guān)于構(gòu)造器的實(shí)例
class Food{
var name: String
init(name: String){
self.name = name
}
convenience init(){
self.init(name: "[Unnamed]")
}
}
let namedMeat = Food(name:"Bacon")
// namedMeat.name = "Bacon"
let mysteryMeat = Food()
// mysteryMeat.name = "[Unnamed]"
class RecipeIngRedient: Food{
var quantity: Int
init(name: String, quantity: Int){
self.quantity = quantity
super.init(name: name)
}
// 這里其實(shí)是重寫了 父類的 designated 構(gòu)造器 init(name:String)
convenience override init(name: String) {
self.init(name: name, quantity: 1)
}
}
let oneMysteryItem = RecipeIngRedient()
let oneBacon = RecipeIngRedient(name: "Bacon")
let sixEggs = RecipeIngRedient(name: "Eggs", quantity: 6)
class ShoppingListItemA: RecipeIngRedient{
var purchased = false
var description: String{
var output = "\(quantity) x \(name)"
output += purchased ? "?" : "?"
return output
}
}
var breakfastList = [
ShoppingListItemA(),
ShoppingListItemA(name: "Bacon"),
ShoppingListItemA(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList{
print(item.description)
/*
1 x Orange juice?
1 x Bacon?
6 x Eggs?
*/
}
// --------------- 構(gòu)造器失敗 -------------
// 類, 結(jié)構(gòu)體, 枚舉型 都可以初始化失敗. 有可能是非法的參數(shù)值, 或者其他條件的缺失
// 構(gòu)造器失敗可以寫作 init? 失敗時 用return nil 返回
struct AnimalAA{
let species: String
init?(species: String){
if species.isEmpty{return nil}//構(gòu)造器失敗 返回nil
self.species = species //構(gòu)造器成功不需要 return
}
}
let someCreature = AnimalAA(species: "Giraffe")
// someCreature is of type Animal? not Animal
if let giraffe = someCreature{
print("An animal was initialized with a species of \(giraffe.species)")
// Prints "An animal was initialized with a species of Giraffe
}
let annonymousCreature = AnimalAA(species: "")
// annoymousCreature is of type Animal ? , not Animal
if annonymousCreature == nil{
print("The annonymous creature could not be initialized")
// Prints "The anonymous creature could not be initialized
}
//------------- 枚舉 構(gòu)造器失敗 -------------
// 當(dāng)構(gòu)造枚舉的 key 不匹配任何一個 case 時 我們可以定義這枚舉類型失敗
enum TemperatureUnit{
case kelvin, celsius, fahrenheit
init?(symbol: Character){
switch symbol {
case "K":
self = .kelvin
case "C":
self = .celsius
case "F":
self = .fahrenheit
default:
return nil
}
}
}
let fahrenheitUnit = TemperatureUnit(symbol: "F")
if fahrenheitUnit != nil{
print("This is a defined temperature unit, so initialization succeeded.")
}
// Prints "This is a defined temperature unit, so initialization succeeded."
let unknownUnit = TemperatureUnit(symbol: "X")
if unknownUnit == nil{
print("This is not a defined temperature unit, so initialization failed.")
}
// Prints "This is not a defined temperature unit, so initialization failed.”
//-------------- 用原始值構(gòu)造枚舉失敗 -----------
enum TemperatureUnitA: Character{
case kelvin = "K", celsius = "C", fahrenheit = "F"
}
let fahrenheitUnitA = TemperatureUnitA(rawValue: "F")
if fahrenheitUnitA != nil{
print("This is a defined temperature unit, so initialization succeeded.")
}
// Prints "This is a defined temperature unit, so initialization succeeded.”
let unknownUnitB = TemperatureUnitA(rawValue: "X")
if unknownUnitB == nil {
print("This is not a defined temperature unit , so initialization failed.")
}
// Prints "This is not a defined temperature unit, so initialization failed."
//-------------- 構(gòu)造器失敗傳播---------
class Product{
let name :String
init?(name: String){
if name.isEmpty { return nil }
self.name = name
}
}
class CartItem: Product{
let quantity: Int
init?(name: String, quantity: Int){
if quantity < 1 { return nil }
self.quantity = quantity
super.init(name: name)
}
}
// 用合法的 quantity 創(chuàng)建構(gòu)造器
if let twoSocks = CartItem(name: "sock", quantity: 2){
print("Item: \(twoSocks.name), quantity: \(twoSocks.quantity)")
}
// Print "Item: sock, quantity: 2"
//使用非法的 quantity 創(chuàng)建構(gòu)造器
if let zeroShirts = CartItem(name: "shirt", quantity: 0) {
print("Item: \(zeroShirts.name), quantity: \(zeroShirts.quantity)")
} else {
print("Unable to initialize zero shirts")
}
//Print "Unable to initialize zero shirts"
// 使用非法的 name 創(chuàng)建構(gòu)造器, 父類構(gòu)造器失敗,導(dǎo)致該類構(gòu)造器失敗
if let oneUnnamed = CartItem(name: "", quantity: 1) {
print("Item: \(oneUnnamed.name), quantity: \(oneUnnamed.quantity)")
} else {
print("Unable to initialize zero shirts")
}
//Prints "Unable to initialize zero shirts"
//------------ 重寫構(gòu)造器失敗 ------------
// 當(dāng)父類是可以失敗的構(gòu)造器時
// 如何確保子類的構(gòu)造器一定是成功的呢!
// 只要子類不滿足造成父類構(gòu)造器失敗的條件即可
class Document{
var name: String?
// name 可選值, 可為 nil
init(){}
init?(name: String) {
if name.isEmpty { return nil }
self.name = name
}
}
class AutomaticallyNamedDocument: Document{
override init() {
super.init()
self.name = "[Untitled]"
}
override init(name: String){
// 沒有調(diào)用會讓父類構(gòu)造器失敗的 方法 `init(name: String)`
super.init()
if name.isEmpty {
// 給 name 一個默認(rèn)值,
self.name = "[Untitled]"
} else {
self.name = name
}
}
}
class UntitledDocument: Document{
override init() {
// 如果這里寫作 super.init(name: "") 編譯器回報錯, 因?yàn)檫@樣寫沒意義
super.init(name: "[Untitled]")!// 強(qiáng)制解包
}
}
// ------- 父類構(gòu)造器可能失敗,子類構(gòu)造器一定成功 init!-----
// 當(dāng)使用 init! 時, 必須確定該類一定有值, 如果該類為 nil 則會拋出異常
// --------- 要求實(shí)現(xiàn)的構(gòu)造器 ------------
// 用關(guān)鍵字 required 修飾的構(gòu)造器是子類必須重寫的的構(gòu)造器
// 重寫 required 的構(gòu)造器 不需要 override 關(guān)鍵字
class SomeClass {
required init() {
}
}
class SomeSubclass: SomeClass{
//重寫父類構(gòu)造器 沒有 override
required init() {
//
}
}
// ---------- 用 閉包 和 方法 給屬性設(shè)置默認(rèn)值
// class SomeClassA {
//
// let someProperty: Sometype = {
// // create a default value for someProperty inside this closure
// // someValue must be of the same type as SomeType”
//
// return someValue
// }()
//
// }
// 上面的代碼, 屬性 someProperty 默認(rèn)值是閉包的返回值.
// 如果沒有最后 的小括號() 屬性 someProperty 的 值 是一個閉包(不是返回值)
// 小括號還有一個作用, 讓閉包立即運(yùn)行, 返回結(jié)果
struct Chessboard {
let boardColors: [Bool] = {
var temporaryBoard = [Bool]()
var isBlack = false
for i in 1...8 {
for j in 1...8 {
temporaryBoard.append(isBlack)
isBlack = !isBlack
}
isBlack = !isBlack
}
return temporaryBoard
}()
func squareIsBlackAt(row: Int, column: Int) -> Bool{
return boardColors[(row * 8) + column]
}
}
let board = Chessboard()
print(board.squareIsBlackAt(row: 0, column: 1))
//true
print(board.squareIsBlackAt(row: 7, column: 7))
//false
Swift - 構(gòu)造器
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門纤泵,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人镜粤,你說我怎么就攤上這事夕吻。” “怎么了繁仁?”我有些...
- 文/不壞的土叔 我叫張陵涉馅,是天一觀的道長。 經(jīng)常有香客問我黄虱,道長稚矿,這世上最難降的妖魔是什么? 我笑而不...
- 正文 為了忘掉前任捻浦,我火速辦了婚禮晤揣,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘朱灿。我一直安慰自己昧识,他們只是感情好,可當(dāng)我...
- 文/花漫 我一把揭開白布盗扒。 她就那樣靜靜地躺著跪楞,像睡著了一般缀去。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上甸祭,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼寨典!你這毒婦竟也來了氛雪?” 一聲冷哼從身側(cè)響起,我...
- 序言:老撾萬榮一對情侶失蹤凝赛,失蹤者是張志新(化名)和其女友劉穎注暗,沒想到半個月后坛缕,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體墓猎,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年赚楚,在試婚紗的時候發(fā)現(xiàn)自己被綠了毙沾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
- 正文 年R本政府宣布,位于F島的核電站俭嘁,受9級特大地震影響躺枕,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜供填,卻給世界環(huán)境...
- 文/蒙蒙 一拐云、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧近她,春花似錦叉瘩、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽危彩。三九已至,卻和暖如春捅暴,著一層夾襖步出監(jiān)牢的瞬間恬砂,已是汗流浹背。 一陣腳步聲響...
- 正文 我出身青樓梧奢,卻偏偏與公主長得像狱掂,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子亲轨,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- 構(gòu)造過程:是使用類趋惨、結(jié)構(gòu)體或枚舉類型的實(shí)例之前的準(zhǔn)備過程。在新實(shí)例可用前必須執(zhí)行這個過程惦蚊,具體操作包括設(shè)置實(shí)例中每...
- 前言:前段時間想為系統(tǒng)類extension一些init方法器虾,編譯器報錯不能為該類添加指定指定構(gòu)造器,并讓我在ini...
- 1.Food類 它創(chuàng)建了兩個構(gòu)造器類蹦锋,一個為指定構(gòu)造器兆沙,一個為便利構(gòu)造器。指定構(gòu)造器保證了所有的存儲屬性都進(jìn)行了初...
- 這段時間用Swift寫項(xiàng)目時候便發(fā)現(xiàn)它的構(gòu)造函數(shù)相比OC真的是復(fù)雜了許多,加了很多的限制和條件,不過這么設(shè)計(jì)...