LoginSignup
0
0

More than 5 years have passed since last update.

同一スコープに同じ名前でタイプエイリアスと変数があるとSwiftが混乱する

Posted at

便所の落書きレベルなので、クソ暇な人は、暇つぶしにどうぞ。以下のように同じスコープ内に同じ名前のタイプエイリアスと変数が共存するときにはタイプエイリアスが勝つみたいです。

private let ID = "id"

struct Book {

    typealias ID = String

    let dict: [String:String] = ["id":"114514", "name":"1919"]

    var id: String {
        return dict[ID] 
        //=> Cannot convert value of type '(Book.ID).Type'(aka 'String.Type') to expected argument type 'DictionaryIndex<_, _>'
    }

}

では、もうちょっと親切に dict へのキー指定に index(forKey: String) を使ってみれば、さすがに大丈夫なのかなと思ったのですが、そうでもなかった。

private let ID = "id"

struct Book {

    typealias ID = String

    let dict: [String:String] = ["id":"114514", "name":"1919"]

    var id: String {
        return dict.index(forKey: ID)
        //=> Cannot convert value of type '(Book.ID).Type'(aka 'String.Type') to expected argument type 'DictionaryIndex<_, _>'

    }

}

おとなしくどっちかの名前を変えてあげることで対応しました。Swiftでのプログラミングは楽しいですね!!!!!

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0