相关疑难解决方法(0)

确定Swift字典是否包含密钥并获取其任何值

我目前正在使用以下(笨拙的)代码片段来确定(非空)Swift字典是否包含给定密钥以及从同一字典中获取一个(任何)值.

怎么能把这个更优雅地放在Swift中呢?

// excerpt from method that determines if dict contains key
if let _ = dict[key] {
    return true
}
else {
    return false
}

// excerpt from method that obtains first value from dict
for (_, value) in dict {
    return value
}
Run Code Online (Sandbox Code Playgroud)

dictionary swift

238
推荐指数
4
解决办法
19万
查看次数

Swift中的两个(或更多)选项

在观看Apple关于LLDB调试器的视频时,我发现了一些我无法找到解释的内容; 当他写道时,他正在谈论可选值:

var optional: String? = nil; //This is ok, a common optional
var twice_optional: String?? = nil; //What is this and why's this useful??
Run Code Online (Sandbox Code Playgroud)

我打开了一个游乐场并开始尝试它,并意识到你可以根据需要编写任意?数量的游戏,然后用相同的数量打开它们!.我理解包装/解包变量的概念,但不能想到我想要包装值4,5或6次的情况.

optional ios swift

15
推荐指数
1
解决办法
1126
查看次数

Nil检查并不总是在Swift中为Any工作

当我使用Any类型时,我对Swift如何检查nil感到困惑.
这是一个例子:

let testA: Any? = nil
let testB: Any = testA as Any
let testC: Any? = testB

if testA != nil {
    print(testA) // is not called as expected
}
if testB != nil {
    print(testB) // prints "nil"
}
if testC != nil {
    print(testC) // prints "Optional(nil)"
}
Run Code Online (Sandbox Code Playgroud)

testA按预期工作.变量为nil,因此条件为false.

testB的工作并不像预期的那样.变量为nil,如打印调用所示.但条件testB != nil评估为真.为什么会这样?

testC也困惑我,因为它是testC = testB = testA.那么为什么它的行为与testA不同呢?

我怎么需要写if条件if testB ...if testC ...不是真的.
我正在寻找一种不需要我知道类型的解决方案,比如......

if let …
Run Code Online (Sandbox Code Playgroud)

swift

9
推荐指数
1
解决办法
296
查看次数

为什么nil合并算子?返回零?

请考虑以下涉及nil合并运算符的 示例??:

let mysteryInc = ["Fred": "Jones", "Scooby-Doo": nil]

let lastname = mysteryInc["Scooby-Doo"] ?? "no last name"

print(lastname == nil)  // true
Run Code Online (Sandbox Code Playgroud)

如最后一个print语句所示,nil合并运算符的结果是nil.

如果nil coalescing运算符应该解包一个Optional,为什么它会返回nil

optional swift

5
推荐指数
1
解决办法
614
查看次数

标签 统计

swift ×4

optional ×2

dictionary ×1

ios ×1