Swift學習(一):自訂運算子 operator

來源:互聯網
上載者:User

標籤:

自訂運算子僅能包含這些字元:

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

 

運算子位置:

前置運算子    prefix中間運算子    infix後置運算子    postfix

 

運算子其他配置

結合性        associativity可取值範圍    left,right和none優先順序        precedence可取值範圍    0~255系統內建運算子結合性質及優先順序    求冪相關(無結合,優先順序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     類型轉換 (無結合,優先順序 132)        is 類型檢查( 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次方,左結合,優先順序為255infix operator ^^ {associativity left precedence 255}func ^^(left: Double, right: Double) -> Double {    return pow(left, right)}println(2 ^^ 10 - 2 ^^ 3)  // 1024 - 8 = 1016

 

Swift學習(一):自訂運算子 operator

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.