Skip to content

Instantly share code, notes, and snippets.

@omochi
Created May 23, 2017 09:38
Show Gist options
  • Save omochi/53deae52ce3622fad56f90cba6f5e746 to your computer and use it in GitHub Desktop.
Save omochi/53deae52ce3622fad56f90cba6f5e746 to your computer and use it in GitHub Desktop.
protocol MagicProtocol {
associatedtype AT1
func getAT1Value() -> AT1
}
// EXT1: 普遍的
extension MagicProtocol {
func getAT1Value() -> Array<Int> {
return [1, 2, 3]
}
}
// EXT2: 条件String
extension MagicProtocol where AT1 == String {
func getAT1Value() -> String {
return "AT1 is String"
}
}
// EXT3: 条件Int
extension MagicProtocol where AT1 == Int {
func getAT1Value() -> Int {
return 32
}
}
// 型の方では何も実装しない
struct MagicDog : MagicProtocol {}
func hoge<X: MagicProtocol>(x: X) {
print(x.getAT1Value())
}
hoge(x: MagicDog())
/*
EXT1, 2, 3をそれぞれコメントアウトで消したりすると
どれも無い時: エラー
EXT1だけ: Array<Int>になる (わかる)
EXT2だけ: Stringになる (わからない・・・亜空間)
EXT3だけ: Intになる (わからない・・・亜空間)
EXT1とEXT2: Stringになる (わからない・・・普遍より亜空間が強い)
EXT1とEXT3: Intになる (わからない・・・普遍より亜空間が強い)
EXT2とEXT3: エラー、StringとIntで曖昧と言われる (ややわかる)
EXT1とEXT2とEXT3: エラー、StringとIntで曖昧と言われる
*/
@omochi
Copy link
Author

omochi commented May 23, 2017

extensionの中の StringIntAT1 と、エイリアス名そのままで書くと、亜空間推論が起きないようだ。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment