Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

swift - Perform assignment only if right side is not nil

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:

if let unwrapped = funcThatReturnsOptional() {
    object.nonOptionalProperty = unwrapped
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...