2014-06-09 72 views
0

我看所有的教程迅速從蘋果,但我在使用的一個例子問題:選配在迅速

class Person { 
    var residence: Residence? 
} 

class Residence { 
    var address: Address? 
} 

class Address { 
    var buildingNumber: String? = "234" 
    var streetName: String? = "Main St." 
    var appartmentNumber: String? 
} 

let paul = Person() 
var addressNumber: Int? 

addressNumber = paul.residence?.address?.buildingNumber?.toInt() 

if let number = addressNumber { 
    "correct" 
} else { 
    "fault" 
} 

它總是打印出「故障」。我錯過了一些顯而易見的東西嗎?

+0

'if let number = addressNumber'是什麼?這是一項任務嗎? 「故障」是否表明分配失敗? –

+1

是的,首先,'住所'從來沒有被分配到價值 – Alladinian

回答

2

那麼你從來沒有真正建立一個有效的ResidenceAddress,如果你改變你的代碼:

class Person { 
    // actually create a residence object 
    var residence: Residence? = Residence() 
} 

class Residence { 
    // actually create a address object 
    var address: Address? = Address() 
} 

class Address { 
    // ... 
} 

let paul = Person() 
var addressNumber: Int? 

// Before Paul was never assigned a valid residence, now one will be created 
addressNumber = paul.residence?.address?.buildingNumber?.toInt() 

if let number = addressNumber { 
    "correct" 
} else { 
    "fault" 
} 
// gives you `correct` 

那麼它應該很好!

+0

這真的很痛苦明顯。謝謝,以及所有指出它的人! –

+1

@ Nilzone-yup,沒問題!它發生在我們所有人的某個點或另一個地方! – Firo

1

您從不初始化除Person()之外的任何內容,因此paul上的residence屬性爲nil

因此,在下面的可選鏈:

addressNumber = paul.residence?.address?.buildingNumber?.toInt() 
          ^you get nil here and don't continue 

這意味着addressNumbernil

2
let paul = Person() 

你別做任何事情paul包括設置他可選的居住變量。因此,在下一行代碼中,您正在訪問paul的住所,即nil

addressNumber = paul.residence?.address?.buildingNumber?.toInt() 
        ^failing right here, residence? returns nil 

因此,與可選的鏈接,這整個表達式返回nil,所以在你的下一個if let聲明相比時,那是假的。這就是爲什麼else子句正在執行。

2

想一想,一次一個腳印。特別是,您可選鏈接:

addressNumber = paul.residence?.address?.buildingNumber?.toInt()

問自己:

  1. 什麼是paul

  2. 什麼是paulresidence屬性設置爲?

  3. 什麼是addresspaulresidence

提示:你不應該讓過去的第2步