swift3对成员下标的模糊引用

时间:2016-12-03 15:02:50

标签: ios swift swift3

我知道这个问题一直在问无数次,但我仍然在努力寻找答案。这是我在代码中最简单的例子,即使我的其余代码也因为我升级到Swift 3而出现这个错误。

func generateDummyPlayers(numberOfPlayers: Int32) -> [NSString : Player] {
    var _players = [NSString : Player]()
    if(numberOfPlayers) > 0 {
        for i in 1...numberOfPlayers {
            let name: String = "\(Player.prefix) \(i)";
            let player: Player = Player(name: name);
            _players[name] = player; //Ambiguous reference to member 'subscript'
        }
    }
    return _players;
}

2 个答案:

答案 0 :(得分:3)

您将字典定义为[NSString: Player],但您的密钥为String

var _players = [NSString : Player]()
let name: String = "\(Player.prefix) \(i)"

_players[name] = player // Error

如果您不需要与ObjC互动,请使用String

var _players = [String : Player]()

答案 1 :(得分:0)

name是一个字符串,因此它不是NSString。您可以将方法签名更改为仅使用String(推荐):

func generateDummyPlayers(numberOfPlayers: Int32) -> [String : Player] {
    var players = [String : Player]()
    if numberOfPlayers > 0 {
        for i in 1...numberOfPlayers {
            let name = "\(Player.prefix) \(i)"
            let player = Player(name: name)
            players[name] = player
        }
    }
    return players
}

您可以在需要时将name更改为NSString(不推荐):

_players[name as NSString] = player

你也可以使用更多的抽象(但我不鼓励它,因为reduce is less performant due to the struct copy cost):

func generateDummyPlayers(numberOfPlayers: Int32) -> [String : Player] {
    guard numberOfPlayers > 0 else {
        return [:]
    }
    return (1...numberOfPlayers)
        .map({ "\(Player.prefix) \($0)" })
        .reduce([:]) {
            var players = $0
            players[$1] = Player(name: $1)
            return players
    }
}