Perform assignment only if right side is not nil

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

    A single expression with the same effect as your code is

    funcThatReturnsOptional().map { object.nonOptionalProperty = $0 }
    

    but your code is definitely better readable.

    Here the map() method of Optional is used and the closure is executed only if the function does not return nil.

提交回复
热议问题