仅当右侧不为零时才执行赋值 [英] Perform assignment only if right side is not nil

查看:26
本文介绍了仅当右侧不为零时才执行赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果右侧不为零,是否有可能仅执行分配(例如分配给非可选属性)?我正在寻找一种单行表格:

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
}

推荐答案

与您的代码效果相同的单个表达式

A single expression with the same effect as your code is

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

但你的代码绝对可读性更好.

but your code is definitely better readable.

这里使用了Optionalmap()方法,闭包是仅当函数不返回 nil 时才执行.

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

这篇关于仅当右侧不为零时才执行赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆