Swift重载运算符、定义自己的运算符。

一、重载系统已存在的运算符。

swift中可以识别的运算符 + - * / % += -= ++ & |  >  >=   <    <= 

这些运算符相当于一个方法名,可以用来定义

                         名字相同:运算符

                         参数个数:运算符为前置或者后置,一个参数,中置时两个参数。

                         参数类型不同:根据自己需要定义

的不同重载方法。

exp: 

// function 1
func + (left:[Int],right:[Int]) -> Int{
    return 12;
}
// function 2
func + <T:Equatable> (left:T,right:T) -> Int{
    return 16;
}
// function 3
func + (left:[String],right:[String]) -> Int{
    return 12;
}
// function 4
func + (left:Int,right:Int?) -> Int{
    return 12;
}

 此时执行

let b:Int = [1,2] + [4,5]; //12

 function1 和 function2 都满足调用条件,根据结果看,此时程序优先调用的是function1。只有function2时调用function2方法。

   顺便探究了一下,swift中方法判断重复的条件 ( 方法名不同 || 参数个数不同 || 参数类型不同 ||  参数外部调用名字不同)。

下面这种写法会导致程序错误

        func + (left:Int,right:Int) -> Int{
            return 12;
        }
        let a = 2 + 3;        // Ambiguous use of operator '+'

因为系统中已经存在了这样的函数,函数名、参数个数、参数类型、外部调用参数名(空)

二、定义自己的运算法

//前置
prefix operator +++
prefix func +++(target:Int) -> Int {
    return 100;
}

//后置
postfix operator +++
postfix func +++(target:Int) -> Int {
    return 100;
}

//中置
infix operator +++
func +++(left:Int,right: Int) -> Int {
    return left + right + left + right;
}

  随便定义。

  

猜你喜欢

转载自www.cnblogs.com/beautylcy/p/8921812.html