简体   繁体   English

Swift 3:Class和Struct可选

[英]Swift 3: Class and Struct Optionals

I'm transitioning to Swift 3 from coding Obj-c for a long time. 我已经很长时间从编码Obj-c过渡到Swift 3了。 So I think I understand the idea of optionals but I'm confused on this problem. 所以我想我理解可选的想法,但是我对这个问题感到困惑。 Say I have a class called Monster. 假设我有一个名为Monster的课程。 And I also have struct called Town. 我也有一个叫做Town的结构。

struct Town {
    var population: Int = 0
    var name: String?
    var hasSherrif: Bool?
    var hasTheater: Bool?
    var hasTownhall: Bool?
    var hasSchool: Bool?
    var hasGeneralStore: Bool?
    var numOfHomes: Int = 0
}

and Monster... 还有怪物

class Monster {
    var town: Town?
    var name: String?

    func moveToTown(_ thisTown: Town) {
        town = thisTown
        if let strName = name, let strTownName = town?.name {
            print("\(strName) moved to \(strTownName)")
        } else if let strName = name {
            print("\(strName) move to a town with no name")
        } else {
            print("The monster moved to a town. Might help if you give stuff names, just saying.")
        }

    }
}

In moveToTown(_ thisTown: Town), how can I check if Monster has no name but Town does? 在moveToTown(_ thisTown:Town)中,如何检查Monster是否没有名字,而Town是否呢? I'd like to change this line: 我想更改此行:

} else if let strName = name {

to something like

} else if let strName = name && town?.name == nil {

and then add another conditional 然后添加另一个条件

} else if strName == nil && let strTownName = town?.name {
}

Thanks and if there's anything in general that could be cleaned up feel free to critique. 谢谢,如果有什么需要清理的地方,随时可以批评。

You can't use town?.name because town is not optional. 您不能使用town?.name因为town不是可选的。

And no need for the town = thisTown line. 无需town = thisTown行。 Just name the parameter as town . 只需将参数命名为town

I would write it this way: 我会这样写:

func moveToTown(_ town: Town) {
    if let name = name {
        if let townName = town.name {
            print("\(name) moved to \(townName)")
        } else {
            print("\(name) move to a town with no name")
        }
    } else {
        print("The monster moved to a town. Might help if you give stuff names, just saying.")
    }
}

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

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