Swift 算術加算演算子のオーバーロード

sample1-1

let int1:Int=10
let int2:Int=20
let plus:Int=int1+int2
print(plus)
30

sample1-1は、Int型の変数int1,int2に値をセットして+演算子(算術加算演算子)で加算して結果を表示する、という何の変哲もないコードです。まさに何の変哲もないのですが、

つまり+演算子に関して我々が全く何の実装もせずに、当たり前に加算が行われている、ということですね。

このようにInt型ではプログラマは+演算子に関して何も実装せずとも、普通に加算が行われるわけですが、これが自分で作った型の場合はどうか。


sample1-2

struct Container {
    var width:Int=0
    var height:Int=0
}

let con1=Container(width:10,height:20)
let con2=Container(width:20,height:30)

print(con1+con2)

 

main.swift:17:11: error: binary operator '+' cannot be applied to two 'Container' operands
print(con1+con2)
      

Swift ジェネリクスとオーバーロード

汎用的な関数・メソッドを作りたい

汎用的とは?汎用的とは国語的には「広くいろいろな方面に用いること」のような意味ですが、この場合の汎用的は、「複数の種類の型の引数を受け取れる関数・メソッド」くらいの意味でしょうか。

sample1-1

func plus(_ x:Int,_ y:Int)->Int{
    return x+y
}

print(plus(1,1))
print(plus(1,12))
2
13

sample1-1はInt型の二つの引数x,yを受け取り、その和を返す関数plus()を定義しています。上記のようにx,yにInt型の引数が渡された場合その和を得ることができます。


sample1-2

func plus(_ x:Int,_ y:Int)->Int{
    return x+y
}

print(plus(1,1.2))
main.swift:7:14: error: cannot convert value of type 'Double' to expected argument type 'Int'
print(plus(1,1.2))
             ^~~
             Int(