斯威夫特 - 期待' {'启动setter定义

时间:2014-06-09 12:33:01

标签: swift

我正在关注先进的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

2 个答案:

答案 0 :(得分:5)

省略你的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
    }
}

答案 1 :(得分:0)

不要传递参数来设置

set  { 
    exits[direction] = newValue
}