2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Generics、typealiasを組み合わせた時のif let as? の挙動

Last updated at Posted at 2015-07-01

「特定のクラスのときにnilを正常側で扱いたい」というような処理を書いていた時に遭遇したのでメモ
どれもAnyでas?キャストを行っているはずが、test1 のときだけ結果が異なる。。


protocol Prot {
    typealias Test
}

// Generics + typealiasを使ったas?チェック
func test1<T: Prot>(prot: T, any: AnyObject?) -> Bool {
    
    if let any = any as? T.Test {
        return true
    }
    return false
}

// 通常のパターン
func test2<T: Prot>(prot: T, any: AnyObject?) -> Bool {
    
    if let any = any as? Any {
        return true
    }
    return false
}

// typealiasを使ったas?チェック
typealias AliasAny = Any
func test3<T: Prot>(prot: T, any: AnyObject?) -> Bool {
    
    if let any = any as? AliasAny {
        return true
    }
    return false
}


struct A: Prot {
    typealias Test = Any
}

let aaa: Int? = nil
test1(A(), aaa) //false !?
test2(A(), aaa) //true
test3(A(), aaa) //true

2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?