Skip to content

Instantly share code, notes, and snippets.

@omochi
Created March 23, 2017 04:38
Show Gist options
  • Save omochi/90326839d097cc162c0d7e30d5f5e9bb to your computer and use it in GitHub Desktop.
Save omochi/90326839d097cc162c0d7e30d5f5e9bb to your computer and use it in GitHub Desktop.
extension Int {
func onlyIntMethod() -> Int {
return self + 1
}
}
func onlyIntFunc(_ x: Int) -> Int {
return x + 1
}
extension Optional where Wrapped : SignedInteger {
func onlyOptIntMethod() -> Int {
return (self.map { numericCast($0) } ?? 0) + 1
}
}
func onlyOptIntFunc(_ x: Int?) -> Int {
return (x ?? 0) + 1
}
// IntとInt?の両方にオーバロードされた関数
func commonIntFunc(_ x: Int) -> Int {
print(1)
return x + 1
}
func commonIntFunc(_ x: Int?) -> Int {
print(2)
return (x ?? 0) + 1
}
let x: Int! = Optional.some(3)
// Int への暗黙キャストしてメソッド呼び出し
x.onlyIntMethod()
// コンパイルエラー!
// メソッド呼び出しにおいては Int?への暗黙キャストはされない
// c.onlyOptIntMethod()
// Int? への 明示的キャストはできる
(x as Int?).onlyOptIntMethod()
// Int への暗黙キャストして関数呼び出し
onlyIntFunc(x)
// Int? への暗黙キャストして関数呼び出し
onlyOptIntFunc(x)
// Int? への暗黙キャストとして関数呼び出し
// Int? より Int が優先された
commonIntFunc(x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment