返回值不符合方法返回类型,但仍然有效

时间:2016-11-18 19:12:46

标签: swift optional-binding optional-chaining

以下代码段简化自官方文档的Optional Chaining章节。

简而言之,类具有地址类型的可选存储属性address。通过提供部分/全部属性buildingNamebuildingNumberstreet,可以调用地址类型中的 buildingNumber 功能并返回类型为可选String的计算建筑物标识符。

class Person {
    var address: Address?
}

class Address {
    var buildingName: String?
    var buildingNumber: String?
    var street: String?

    func buildingIdentifier() -> String? {
        if buildingNumber != nil && street != nil {
            return "\(buildingNumber) \(street)" //return type is String? String?
        } else if buildingName != nil {
            return buildingName
        } else {
            return nil
        }
    }
}

let john = Person()
john.address = Address()

let theAddress = Address()
theAddress.buildingNumber = "A12"
theAddress.street = "Sunset Street"
john.address = theAddress

if let johnAddressID = john.address?.buildingIdentifier() {
    print("\(johnAddressID)") //##
}

让我们关注函数 buildingIdentifier()中的行return "\(buildingNumber) \(street)"

问题1

函数的返回类型是一个可选的String,但是函数体的返回值是2个可选的String,为什么允许这样做? (请参阅下图,这是上面代码中##标记的行的打印结果)

enter image description here

问题2

我已经使用了可选的绑定表达式( if let ),并且binging看起来很成功,但是为什么johnAddressID没有被解包呢?

感谢您的停留和帮助

0 个答案:

没有答案