Perform assignment only if right side is not nil

后端 未结 5 1628
不思量自难忘°
不思量自难忘° 2020-12-06 05:35

Is there a possibility to only perform an assignment (e.g. to a non-optional property) if the right hand side is not nil? I am looking for a one-line form for:



        
5条回答
  •  囚心锁ツ
    2020-12-06 06:11

    The answer from @Sajjon could be improved by using an if let to avoid reflection.

    precedencegroup OptionalAssignment { associativity: right }
    
    infix operator ?= : OptionalAssignment
    
    public func ?= (variable: inout T, value: T?) {
        if let value = value {
            variable = value
        }
    }
    
    

提交回复
热议问题