Swift IF LET 如何评估? [英] How is Swift IF LET evaluated?

查看:27
本文介绍了Swift IF LET 如何评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Swift 网站上看到了这段代码,在这里也看到了各种帖子,我正在努力掌握基础知识.如何评价这条线?

I've seen this code on the Swift site and various posts here and I am trying to grasp the basics. How is this line evaluated?

if let name = optionalName {

我很困惑,因为它不是 name == 可选名称,它正在分配值,那么如何报告 true 和为什么当你用 nil 替换 john appleseed 时它不是真的,因为它仍然是相等的?

I'm confused as it's not name == optional name, it's assigning the value, so how does that report true and why is it not true when you replace with john appleseed with nil, as its still going to be equal?

var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello, (name)"
}

推荐答案

本质上这句话是说,如果你能让新变量 name 等于 optionalName 的非可选版本,用它做下面的事情".正如 Martin 指出的,这称为 Optional Binding.

Essentially the line is saying, "if you can let the new variable name equal the non-optional version of optionalName, do the following with it". As Martin pointed out, this is called Optional Binding.

它的唯一目的是测试可选变量是否包含实际值并将非可选形式绑定到临时变量.这是解包"可选值的安全方法,或者换句话说,访问可选值中包含的值.它绝不是测试任何类型的平等.它只是测试一个可选值是否存在.

The sole purpose of it is to test if an optional variable contains an actual value and bind the non-optional form to a temporary variable. This is the safe way to "unwrap" an optional or in other words, access the value contained in the optional. It is in no way testing for equality of any kind. It is only testing for the existence of a value within an optional.

这篇关于Swift IF LET 如何评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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