Swift學習(一):自定義運算符 operator


自定義運算符僅能包含這些字符:

/ = - + * % < >!& | ^。~

 

運算符位置:

前置運算符    prefix
中間運算符    infix
后置運算符    postfix

 

運算符其他配置

結合性        associativity
可取值范圍    left,right和none

優先級        precedence
可取值范圍    0255

系統內置運算符結合性質及優先級
    求冪相關(無結合,優先級160)
        << 按位左移(Bitwise left shift)
        >> 按位右移(Bitwise right shift)
 
    乘除法相關(左結合,優先級150)
        */% 求余
        &* 乘法,忽略溢出( Multiply, ignoring overflow)
        &/ 除法,忽略溢出(Divide, ignoring overflow)
        &% 求余, 忽略溢出( Remainder, ignoring overflow)
        & 位與( Bitwise AND)
 
    加減法相關(左結合, 優先級140)
        +-&+ Add with overflow
        &- Subtract with overflow
        | 按位或(Bitwise OR )
        ^ 按位異或(Bitwise XOR)
 
    Range (無結合,優先級 135)
        .. 半閉值域 Half-closed range
        ... 全閉值域 Closed range
 
    類型轉換 (無結合,優先級 132is 類型檢查( type check)
        as 類型轉換( type cast)
        <= 小於等於
        >大於
        >= 大於等於
        == 等於
        != 不等
        === 恆等於
        !== 不恆等
        ~= 模式匹配( Pattern match)
 
    合取( Conjunctive) (左結合,優先級 120&& 邏輯與(Logical AND)
 
    析取(Disjunctive) (左結合,優先級 110|| 邏輯或( Logical OR)
 
    三元條件(Ternary Conditional )(右結合,優先級 100?: 三元條件 Ternary conditional
 
    賦值 (Assignment) (右結合, 優先級 90= 賦值(Assign)
        *= Multiply and assign
        /= Divide and assign
        %= Remainder and assign
        += Add and assign
        -= Subtract and assign
        <<= Left bit shift and assign
        = Right bit shift and assign
        &= Bitwise AND and assign
        ^= Bitwise XOR and assign
        |= Bitwise OR and assign
        &&= Logical AND and assign
        ||= Logical OR and assign

 

范例

// 前置:返回2的n次方
prefix operator  ^ {}

prefix func ^ (var vector: Double) -> Double {
    return pow(2, vector)
}

println(^5)  // 32.0

// 后置:返回2次方
postfix operator  ^ {}

postfix func ^ (var vector: Int) -> Int {
    return vector * vector
}

println(5^)  // 25


//中間:計算N的M次方,左結合,優先級為255
infix operator ^^ {associativity left precedence 255}

func ^^(left: Double, right: Double) -> Double {
    return pow(left, right)
}

println(2 ^^ 10 - 2 ^^ 3)  // 1024 - 8 = 1016

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM