Perform assignment only if right side is not nil

后端 未结 5 1624
不思量自难忘°
不思量自难忘° 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

    There are various ways that aren't too unwieldy

    Using ?? :

    object.nonOptionalProperty = funcThatReturnsOptional() ?? object.nonOptionalProperty 
    

    Using a function :

    func setNotNil(inout variable:T, _ value:T?)
    { if value != nil { variable = value! } }
    
    setNotNil(&object.nonOptionalProperty, funcThatReturnsOptional())
    

    Using an operator :

    infix operator <-?? { associativity right precedence 90 assignment }
    func <-??(inout variable:T, value:T?)
    { if value != nil { variable = value! } }
    
    object.nonOptionalProperty <-?? funcThatReturnsOptional() 
    

    Using an extension :

    extension Equatable
    { mutating func setNotNil(value:Self?) { if value != nil { self = value! } } }
    
    object.nonOptionalProperty.setNotNil(funcThatReturnsOptional())
    

提交回复
热议问题