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

查看:102
本文介绍了如何评估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 {

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

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 等于非-optional version of optionalName ,用它执行以下操作。正如Martin指出的那样,这被称为可选绑定

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天全站免登陆