Swift 3:类和结构选项

时间:2017-09-05 21:08:51

标签: swift class struct optional

我正在从编写Obj-c转换到Swift 3很长一段时间。所以我认为我理解选项的想法,但我对这个问题感到困惑。假设我有一个名为Monster的课程。我也有一个名为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
}

和怪物......

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

    }
}

在moveToTown(_ thisTown:Town)中,我如何检查Monster是否没有名字,但Town呢?我想改变这一行:

} else if let strName = name {

类似

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

然后添加另一个条件

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

谢谢,如果有任何可以清理的东西,请随意批评。

1 个答案:

答案 0 :(得分:2)

您无法使用town?.name,因为town不是可选的。

不需要town = thisTown行。只需将参数命名为town

我会这样写:

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