What if I want to assign a property to itself?

后端 未结 5 1817
孤街浪徒
孤街浪徒 2020-12-30 00:37

If I attempt to run the following code:

photographer = photographer

I get the error:

Assigning a property to itself

5条回答
  •  星月不相逢
    2020-12-30 01:30

    @vacawama did a great job with all those options. However in iOS 10.3, Apple banned some of these ways and most likely will be doing it in the future again.

    Note: To avoid the risk and future errors, I will use a temporary variable.


    We can create a simple function for that:

    func callSet(_ object: inout T) {
        let temporaryObject = object
        object = temporaryObject
    }
    

    Would be used like: callSet(&foo)


    Or even a unary operator, if there is a fitting one ...

    prefix operator +=
    
    prefix func +=(_ object: inout T) {
        let temporaryObject = object
        object = temporaryObject
    }
    

    Would be used like: +=foo

提交回复
热议问题