ぜのぜ

しりとりしようぜのぜのぜのぜ

129日目

日記

明日こそは中華

今日書いたコード

precedencegroup SomePrecedence {
    higherThan: AdditionPrecedence
    lowerThan: MultiplicationPrecedence
    associativity: left
    assignment: true
}

precedencegroup OtherPrecedence {
    higherThan: AdditionPrecedence
    lowerThan: MultiplicationPrecedence
    associativity: left
    assignment: false
}

infix operator ++=: SomePrecedence
infix operator --=: OtherPrecedence

extension Int {
    static func ++=(lhs: inout Int, rhs: Int) {
        lhs += rhs
    }

    static func --=(lhs: inout Int, rhs: Int) {
        lhs -= rhs
    }
}

struct Some {
    var num = 5
}

var some: Some? = Some()
print("#1")
some?.num ++= 1
print("#2")
some?.num --= 1 // Cannot convert value of type 'Int?' to expected argument type 'Int'
print("#3")
some!.num ++= 1
print("#4")
some!.num --= 1

感想

precedencegroupのassignmentの説明がよくわからなかったが,SwiftのStandard Libraryの代入が伴う演算子は,代入される側の変数にOptional Chainingでアクセスしていても書けるという挙動のことを言っていそう.コードを書いてやっと理解できた.

When set to true, an operator in the corresponding precedence group uses the same grouping rules during optional chaining as the assignment operators from the standard library. Otherwise, when set to false or omitted, operators in the precedence group follows the same optional chaining rules as operators that don’t perform assignment.https://docs.swift.org/swift-book/ReferenceManual/Declarations.html