gpt4 book ai didi

ios - Swift 中的 "unwrapped value"是什么?

转载 作者:行者123 更新时间:2023-11-30 13:23:07 27 4
gpt4 key购买 nike

我正在通过关注 this tutorial 学习适用于 iOS 8/OSX 10.10 的 Swift ,并且术语“展开的值”被多次使用,如本段中所示(在对象和类下):

When working with optional values, you can write ? before operationslike methods, properties, and subscripting. If the value before the ?is nil, everything after the ? is ignored and the value of the wholeexpression is nil. Otherwise, the optional value is unwrapped, andeverything after the ? acts on the unwrapped value. In both cases, thevalue of the whole expression is an optional value.

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") 
let sideLength = optionalSquare?.sideLength

我没明白,在网上搜索没有运气。

这是什么意思?

<小时/>

编辑

从 Cezary 的回答来看,原始代码的输出和最终解决方案(在 Playground 上测试)之间存在细微差别:

原始代码

Original code

塞泽里的解决方案

Cezary's solution

在第二种情况下,父类(super class)的属性显示在输出中,而第一种情况下有一个空对象。

这两种情况的结果不应该是相同的吗?

相关问答:What is an optional value in Swift?

最佳答案

首先,您必须了解什么是可选类型。可选类型基本上意味着变量可以nil

示例:

var canBeNil : Int? = 4
canBeNil = nil

问号表示 canBeNil 可以为 nil

这行不通:

var cantBeNil : Int = 4
cantBeNil = nil // can't do this

要从变量中获取值(如果该值是可选的),您必须解开它。这只是意味着在末尾添加一个感叹号。

var canBeNil : Int? = 4
println(canBeNil!)

您的代码应如下所示:

let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") 
let sideLength = optionalSquare!.sideLength

旁注:

您还可以使用感叹号而不是问号来声明自动解包的选项。

示例:

var canBeNil : Int! = 4
print(canBeNil) // no unwrapping needed

因此修复代码的另一种方法是:

let optionalSquare: Square! = Square(sideLength: 2.5, name: "optional square") 
let sideLength = optionalSquare.sideLength

编辑:

您所看到的差异正是可选值被包装这一事实的症状。它上面还有另一层。 未包装版本仅显示直线对象,因为它是未包装的。

Playground 快速比较:

playground

在第一种和第二种情况下,对象不会自动展开,因此您会看到两个“层”({{...}}),而在第三种情况下,您会看到只有一层 ({...}),因为对象会自动展开。

第一种情况和后两种情况之间的区别在于,如果将 opticalSquare 设置为 nil,则后两种情况会给您带来运行时错误。使用第一种情况的语法,您可以执行以下操作:

if let sideLength = optionalSquare?.sideLength {
println("sideLength is not nil")
} else {
println("sidelength is nil")
}

关于ios - Swift 中的 "unwrapped value"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37548151/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com