简体   繁体   中英

Swift 3: Class and Struct Optionals

I'm transitioning to Swift 3 from coding Obj-c for a long time. So I think I understand the idea of optionals but I'm confused on this problem. Say I have a class called Monster. And I also have struct called 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? 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.

And no need for the town = thisTown line. Just name the parameter as 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.")
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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