简体   繁体   English

快速选购

[英]Optionals in swift

I'm watching all the swift tutorials from Apple, but I'm having problems with one of the examples: 我正在看所有来自Apple的快速教程,但是我对以下示例之一有疑问:

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"
}

It's always printing out "fault". 它总是打印出“故障”。 Is there something painfully obvious I'm missing? 有什么令人痛苦的明显我丢失了吗?

let paul = Person()

You do nothing else to paul including setting his optional residence variable. 你别的什么也不做,以paul ,包括他的设置可选的住所变量。 So in the next line of code, you are accessing paul 's residence which is nil . 因此,在下一行代码中,您将访问paul的住所nil

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

So with optional chaining, this entire expression returns nil , so when compared in your next if let statement, it is false. 因此,通过可选链接,整个表达式返回nil ,因此在下一个if let语句中进行比较时,它为false。 This is why the else clause is being executed. 这就是执行else子句的原因。

Think it through, one step at a time. 仔细思考,一次一步。 Particularly, your optional chaining: 特别是,您的可选链接:

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

Ask yourself: 问你自己:

  1. What is paul ? 什么是paul

  2. What is paul 's residence property set to? paulresidence财产被设定为什么?

  3. What is the address of paul 's residence ? paulresidence是什么address

Hint: You shouldn't make it past step 2. 提示:您不应该超过步骤2。

Well you are never actually creating a valid Residence or Address , if you change your code to: 好吧,如果您将代码更改为:您永远不会真正创建有效的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`

then it should work great! 那么它应该很棒!

You never initialize anything except Person() , so the residence property on paul is nil . 除了Person()之外,您永远不会初始化其他任何东西,因此paul上的residence属性为nil

So, in the following optional chain: 因此,在以下可选链中:

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

This means that addressNumber is nil . 这意味着addressNumbernil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM