Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

closures

swift

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 {

    let region = "South"
    var population = 5422
    var numberOfStoplights = 4

    enum Size {
        case Small
        case Medium
        case Large
    }

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

    func printTownDescription() {
      print("Population: \(myTown.population), number of stoplights: \(myTown.numberOfStoplights)")  
    }

    mutating func changePopulation(amount: Int) {
        population += amount
    }
}
like image 952
pdenlinger Avatar asked Apr 12 '16 16:04

pdenlinger


2 Answers

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.

like image 56
Rob Avatar answered Nov 18 '22 20:11

Rob


You incorrectly declared lazy var it should be declared like this

 lazy var townSize: Size = {
        switch self.population {
        case 0...10000:
            return Size.Small
        case 10001...100000:
            return Size.Medium
        default:
            return Size.Large
        }
    }()
like image 11
Peter K Avatar answered Nov 18 '22 18:11

Peter K