【问题标题】:Swift - expected '{' to start setter definitionSwift - 预期'{'开始设置器定义
【发布时间】:2014-06-09 21:01:08
【问题描述】:

我正在关注高级 swift WWDC 2014 视频,使用类上的下标来委托给类属性,但使用与视频中相同的语法时出现错误

enum Direction {
    case North, South, East, West
}

class Place: Thing {
    init (_ location: Thing?, _ name: String, _ longDescription: String) {
        self.exits = Dictionary<Direction, Place> ()
        super.init(location, name, longDescription)
    }
    var exits: Dictionary<Direction, Place>
}

extension Place {
    subscript(direction: Direction) -> Place? {
        get {
            return exits[direction]
        }
        set (destination: Place?) { // error here
            exits[direction] = destination
        }
    }
}

我得到的错误是

Expected '{' to start setter definition

【问题讨论】:

    标签: swift


    【解决方案1】:

    省略 setter 中的类型,它会自动推断:

    subscript(direction: Direction) -> Place? {
        get {
            return exits[direction]
        }
        set (destination) {
            exits[direction] = destination
        }
    }
    

    您也可以完全跳过该参数,在这种情况下,它被隐式命名为newValue

    subscript(direction: Direction) -> Place? {
        get {
            return exits[direction]
        }
        set {
            exits[direction] = newValue
        }
    }
    

    【讨论】:

    • 是的。 “newValue 的类型与下标的返回值相同”是 The Swift Programming Language 书中指定这一点的行(书中示例中的newValue 是 setter 的参数。)
    【解决方案2】:

    不要传递参数来设置

    set  { 
        exits[direction] = newValue
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      相关资源
      最近更新 更多