错误:条件绑定的初始化程序必须具有可选类型,而不是'String' [英] Error: Initializer for conditional binding must have optional type, not 'String'
本文介绍了错误:条件绑定的初始化程序必须具有可选类型,而不是'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
- 尝试解包
firstName
- 如果解包结果成功,请分配结果展开到
名称
- 如果展开结果成功,请打印
Hello,\(名称) )
- Try unwrapping
firstName
- If the result of unwrapping is successful, assign the result of unwrapping to
name
- 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屋!
查看全文