Cannot convert value of type '() -> _' to specified type 'Town.Size'

前端 未结 2 652
栀梦
栀梦 2021-01-04 17:00

Am getting this issue with this struct, on the line which reads \"lazy var townSize: Size ={\" and can\'t figure out what the issue is.

struct Town {

             


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 17:44

    As has been noted, to initialize a stored property with a closure, you need the () after that closing brace:

    lazy var townSize: Size = {
        switch self.population {
        case 0 ... 10000:
            return .Small
        case 10001 ... 100000:
            return .Medium
        default:
            return .Large
        }
    }()
    

    But, because population is a variable, not a constant, you don't want townSize to be a stored property at all. Instead, you want it to be a computed property, to accurately reflect any changes in the population:

    var townSize: Size {
        switch population {
        case 0 ... 10000:
            return .Small
        case 10001 ... 100000:
            return .Medium
        default:
            return .Large
        }
    }
    

    Note the lack of the =.

    If you use a lazy stored property, if population changes subsequent to accessing townSize, the townSize won't reflect this accordingly. But using a computed property solves this problem.

提交回复
热议问题