• Geek_zoey
    2019-08-29
    老师生病了呀,保重身体
    
     4
  • Life is fantastic
    2019-11-21
    不好意思,前几天学所有权在消化做笔记。今天把这段代码分享给老师和大家,代码来源于互联网,注释为本人注释,如有不对的地方请大家指正,。
    prefix operator +☀
    infix operator +-☀ : PlusMinusPrecedence

    precedencegroup PlusMinusPrecedence {
        associativity: none // 结合性(left\right\none)
        higherThan: AdditionPrecedence //比谁的优先级高
        lowerThan: MultiplicationPrecedence//比谁的优先级低,不能是该模块内部的
        assignment: false //如果设置成true,那么遇到可选链的时候该操作符就相当于赋值操作符。否则false就不执行赋值操作。
    }


    struct Point {
        var x: Int, y: Int
        static prefix func +☀(point: inout Point) -> Point {
            point = Point(x: point.x + point.x, y: point.y + point.y)
            return point
        }
        static func +-☀(left: Point,right: Point) -> Point {
            return Point(x: left.x + right.x, y: left.y - right.y)
        }
        static func +-☀(left: Point?,right: Point) -> Point {
            print("+-☀")
            return Point(x: left?.x ?? 0 + right.x, y: left?.y ?? 0 - right.y)
        }
    }

    struct Person {
        var point: Point //= Point(x: 10, y: 20)
    }
    var person: Person? //= Person.init()
    person?.point +-☀ Point(x: 10, y: 20)//(Point(x: 10, y: 20) +-☀ Point(x: 10, y: 20))
    print(person?.point as Any)
    var test = Point(x: 10, y: 20)
    Point(x: 10, y: 20) +-☀ (+☀test)
    展开

    作者回复: 我把你的例子改了一下,既然是赋值运算,你的实现里明显不是。

    infix operator +-☀ : PlusMinusPrecedence

    precedencegroup PlusMinusPrecedence {
        associativity: none
        higherThan: AdditionPrecedence
        lowerThan: MultiplicationPrecedence
        assignment: true
    }

    struct Point {
        var x: Int, y: Int
        static func +-☀(left: inout Point, right: Point) {
            left = Point(x: left.x + right.x, y: left.y - right.y)
        }
    }

    struct Person {
        var point: Point
    }
    var person: Person?
    person?.point +-☀ Point(x: 10, y: 20)
    print(person?.point as Any)

    你可以尝试把assignment的true改成false,是会报错的,所以assignment的可选链里的作用如下:

    “This proposal quietly drops the assignment modifier that exists on operators today. This modifier had one important function–an operator marked assignment gets folded into an optional chain, allowing foo?.bar += 2 to work as foo?(.bar += 2) instead of failing to type-check as (foo?.bar) += 2. In practice, all Swift operators currently marked assignment are at the equivalent of the Assignment precedence level, so the core team recommends making this optional chaining interaction a special feature of the Assignment precedence group.”

     1
    
  • Life is fantastic
    2019-09-10
    高级运算符文档中,在定义优先级组的时候有个布尔值的属性assignment,设置true的时候有什么讲究。看了人家写的代码可选链为空的时候做赋值运算返回nil,而不是中缀运算了。可以看出这个中缀自定义的运算符相当于赋值运算符了,并不会调用左边形式参数为可选类型的自定义运算。

    作者回复: assignment只是表明是否是赋值,你这个有代码么,拿出来看一下

     1
    
我们在线,来聊聊吧