确定Swift字典是否包含键并获取其任何值 [英] Determining if Swift dictionary contains key and obtaining any of its values

查看:979
本文介绍了确定Swift字典是否包含键并获取其任何值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下(笨拙)代码来确定(非空)Swift字典是否包含给定的键,并从同一个字典中获取一个(任何)值。

I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the same dictionary.

如何在Swift中更加优雅?

How can one put this more elegantly in 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
}


推荐答案

您不需要任何特殊代码来执行此操作,因为它是什么字典已经有。当您获取 dict [key] 您知道字典是否包含密钥,因为您可以返回的可选项不是 nil (它包含的值)。

You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).

所以,如果你只是想回答问题字典包含密钥,请问:

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

如果你想要的值,而你知道,字典包含密钥,说:

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

但是,如果通常发生,您不知道它包含密钥 - 您要获取它使用它,但只有存在 - 然后使用类似如果让

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

这篇关于确定Swift字典是否包含键并获取其任何值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆