Swift 運算子過載和運算子函式

2022-09-05 02:33:10 字數 1472 閱讀 5313

讓已有的運算子對自定義的類和結構進行運算或者重新定義已有運算子的運算規則,這種機制被稱為運算子過載。

1,通過過載加號運算子,使自定義的兩個座標結構體物件實現相加:12

3456

78910

11structcenterpointer

func+ (left:centerpointer, right:centerpointer) ->centerponter

letpointer1 =centerpointer(x:2, y:3)

letpointer2 =centerpointer(x:4, y:5)

letpointer3 = pointer1 + pointer2

2,過載判斷運算子,實現判斷自定義型別是否相等12

3456

7func== (left:centerpointer, right:centerpointer) ->bool

func!= (left:centerpointer, right:centerpointer) ->bool

3,組合運算子,即將其他運算子和賦值運算子組合在一起,注意要把運算子左引數設定成inout型別12

3456

7func+= (inoutleft:centerpointer, right:centerpointer)

varpointer1 =centerpointer(x:2, y:3)

varpointer2 =centerpointer(x:4, y:5)

pointer1 += pointer2

swift 運算子過載

類和結構體可以位現有的運算子提供自定義的實現。成為運算子過載 code a uikit based playground for presenting user inte ce import uikit struct vector2d extension vector2d let vector ve...

swift 過載運算子

1 自定義乙個 運算子,左邊是string型別,右側為int型別 func left string,right int string let b 10 10 println b 0 3 自定義乙個單項事運算子 postfix func left double string println 0.0 4...

Swift 運算子過載專題

import foundation struct vector3 var va vector3 x 1,y 2,z 3 var vb vector3 x 4,y 5,z 6 func left vector3,right vector3 vector3 va vb func left vector3...