sample1-1
let num1=3 let num2=(-num1) print(num2)
-3
2行目で定数num1に対して単項マイナス演算子を作用させています。その結果定数num2に-3がセットされ、表示されています。期待通り、簡単なコードですが、単項マイナス演算子について我々が何の実装もせずに、期待通りの挙動が実現されているわけですね。
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) print(-con1)
main.swift:19:8: error: unary operator '-' cannot be applied to an operand of type 'Container'
print(-con1)
sample1-2では独自の型(構造体)Containerを定義し、インスタンス化、そのインスタンスをセットした定数con1に対して単項マイナス演算子を付けています。結果はエラー。
独自の型に対して単項マイナス演算子を使用できるようにするには、単項マイナス演算子の演算子メソッドを定義する必要があります。
sample2-1
struct Container { var width:Int=0 var height:Int=0 } extension Container{ static prefix func -(con:Container)->Container{ return Container(width:-con.width,height:-con.height) } } let con1=Container(width:10,height:20) let con2=Container(width:20,height:30) print(con1) print(-con1)
Container(width: 10, height: 20)
Container(width: -10, height: -20)