无法转换类型'()->的值_'指定为类型“ Town.Size” [英] Cannot convert value of type '() -> _' to specified type 'Town.Size'

查看:60
本文介绍了无法转换类型'()->的值_'指定为类型“ Town.Size”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此结构上遇到此问题,该行显示为
lazy var townSize:Size = {并且无法弄清楚问题出在哪里。

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
    }
}


推荐答案

As已经注意到,要使用闭包初始化存储的属性,则需要()右括号:

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
    }
}()

但是,因为人口是变量,而不是常量,您根本不希望 townSize 成为存储的属性。相反,您希望它是一个计算属性,以准确反映人口中的任何变化:

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
    }
}

请注意缺少 =

如果使用懒惰存储的属性,如果人口在访问 townSize 之后发生更改,则 townSize 不会相应地反映出来。但是使用计算属性可以解决此问题。

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.

这篇关于无法转换类型'()->的值_'指定为类型“ Town.Size”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆