错误:条件绑定的初始化程序必须具有可选类型,而不是'String' [英] Error: Initializer for conditional binding must have optional type, not 'String'

查看:77
本文介绍了错误:条件绑定的初始化程序必须具有可选类型,而不是'String'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var firstName: String = "John Appleseed"
if let name = firstName {
    print ("Hello, \(name)")
}

String第二行错误:条件绑定的初始化程序必须具有可选类型,而不是'String'

String Error on second line: Initializer for conditional binding must have optional type, not 'String'

如何决定是使用可选变量还是非可选变量?

How to decide whether to use optional or non-optional variables?

推荐答案

首先,让我们考虑一下,如果让构造意味着什么。当你写

First, let's consider what the if let construct means. When you write

if let name = firstName {
    print ("Hello, \(name)")
}

你告诉Swift你想要

you tell Swift that you want to


  1. 尝试解包 firstName

  2. 如果解包结果成功,请分配结果展开到名称

  3. 如果展开结果成功,请打印Hello,\(名称) )

  1. Try unwrapping firstName
  2. If the result of unwrapping is successful, assign the result of unwrapping to name
  3. If the result of unwrapping is successful, print "Hello, \(name)"

换句话说,这个构造用于处理可选变量的展开。但是,变量 firstName 不是可选;什么都没有解开,导致斯威夫特抱怨。

In other words, this construct is for dealing with unwrapping of optional variables. However, variable firstName is not optional; there is nothing to unwrap, causing Swift to complain.

这篇关于错误:条件绑定的初始化程序必须具有可选类型,而不是'String'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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