Avatar
SwiftのDictionaryのキーにプロトコル使えますか?もしくはそういう場面に出くわしたときの代替案はありますか? ユースケースとしては、DictionaryLiteralpairs 変数のキーに ExpressionType を入れたいです。試した方法は下記のリンクとほぼ同じです。 ExpressionType を内部で持つ AnyLiteral みたいなstructを定義する以外の方法が思いつかない... https://forums.developer.apple.com/message/9175#9175 ソースコードの例です。インタープリタを実装していて、Dictionaryリテラルを追加しようとしています。 enum TokenKind: Int, Hashable { case integer case string case dictionary } protocol ExpressionType { var token: TokenKind { get } } struct IntegerLiteral { let value: Int64 } extension IntegerLiteral: ExpressionType { var token: TokenKind { return .integer } } struct StringLiteral { let value: String } extension StringLiteral: ExpressionType { var token: TokenKind { return .string } } struct DictionaryLiteral { let pairs: [ExpressionType: ExpressionType] } extension DictionaryLiteral: ExpressionType { var token: TokenKind { return .dictionary } } (edited)
I'm wondering, is it even possible to create a Set in Swift whose members are guaranteed only to share conformance to a Protocol? My initial attempt