为什么在Swift 3中使用字符串插值时,隐式解包的选项不会被解包?
示例:在操场中运行以下代码
var str: String!
str = "Hello"
print("The following should not be printed as an optional: \(str)")
Run Code Online (Sandbox Code Playgroud)
产生这个输出:
The following should not be printed as an optional: Optional("Hello")
Run Code Online (Sandbox Code Playgroud)
当然我可以用+运算符连接字符串,但我在我的应用程序中几乎无处不在使用字符串插值,现在因为这个而无法工作(bug?).
这甚至是一个bug还是他们故意用Swift 3改变这种行为?
是否可以检查变量是否是可选的,以及它包装的是什么类型?
可以检查变量是否是特定的可选:
let someString: String? = "oneString"
var anyThing: Any = someString
anyThing.dynamicType // Swift.Optional<Swift.String>
anyThing.dynamicType is Optional<String>.Type // true
anyThing.dynamicType is Optional<UIView>.Type // false
Run Code Online (Sandbox Code Playgroud)
但是有可能再次检查任何类型的可选项吗?就像是:
anyThing.dynamicType is Optional.Type // fails since T cant be inferred
// or
anyThing.dynamicType is Optional<Any>.Type // false
Run Code Online (Sandbox Code Playgroud)
一旦知道你有一个可选的,检索它包装的类型:
// hypothetical code
anyThing.optionalType // returns String.Type
Run Code Online (Sandbox Code Playgroud) Swift 新手,我遇到了一个令人沮丧的问题。该程序正确编译并运行而不会崩溃。该程序应该根据用户输入的人类年数计算猫的年龄(以猫年为单位)。然而,按下按钮后,结果会显示“运算符”一词,并附加以括号分隔的猫年,即Optional(35)。这是我的代码:
@IBOutlet weak var getHumanYears: UITextField!
@IBOutlet weak var displayCatYears: UILabel!
@IBAction func calculateCatYears(_ sender: Any)
{
if let humanYears = getHumanYears.text
{
var catYears: Int? = Int(humanYears)
catYears = catYears! * 7
let catYearsString: String = String(describing: catYears)
displayCatYears.text = "Your cat is " + catYearsString + " years old"
}
}
Run Code Online (Sandbox Code Playgroud)
有谁知道我做错了什么?感谢您的宝贵意见!