错误:条件绑定的初始化程序必须具有可选类型,而不是'String'[重复]

时间:2021-08-17 16:36:26

This question already has an answer here:

这个问题在这里已有答案:

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

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

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

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

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

2 个解决方案

#1


3  

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

首先,让我们考虑if let构造的含义。当你写作

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

you tell Swift that you want to

你告诉斯威夫特你想要的

  1. Try unwrapping firstName
  2. 尝试解包firstName

  3. If the result of unwrapping is successful, assign the result of unwrapping to name
  4. 如果解包结果成功,则将展开结果分配给name

  5. If the result of unwrapping is successful, print "Hello, \(name)"
  6. 如果解包结果成功,则打印“Hello,\(name)”

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.

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

#2


2  

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

add ? to make it optional.

加?使它成为可选的。

check answer in this link to know where to use optional and what is actually it is

检查此链接中的答案,了解可选的使用位置以及实际情况

hope this will help :)

希望这会有所帮助:)

#1


3  

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

首先,让我们考虑if let构造的含义。当你写作

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

you tell Swift that you want to

你告诉斯威夫特你想要的

  1. Try unwrapping firstName
  2. 尝试解包firstName

  3. If the result of unwrapping is successful, assign the result of unwrapping to name
  4. 如果解包结果成功,则将展开结果分配给name

  5. If the result of unwrapping is successful, print "Hello, \(name)"
  6. 如果解包结果成功,则打印“Hello,\(name)”

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.

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

#2


2  

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

add ? to make it optional.

加?使它成为可选的。

check answer in this link to know where to use optional and what is actually it is

检查此链接中的答案,了解可选的使用位置以及实际情况

hope this will help :)

希望这会有所帮助:)