Swift 布尔值字典的优雅条件
Swift elegant condition for dictionary with boolean values
抱歉,当我写完这个问题时,我发现它因为一个愚蠢的语法错误而无法正常工作...我还是发布了这个因为
- 答:我觉得有用
- B:也许大家有更好的主意...
试图让事情变得更优雅......我有一个可选的 [String:Bool]
字典和一个字符串键。现在,在一种情况下我想问:
我有字典吗?
请求的密钥是否存在?
是这个键的值 "true"?
解决方法:
var topics:[String:Bool]?
let topicName="Pictures"
if self.topics?[topicName] ?? false {
//do stuff
}
你为什么使用 Boolean
而不是 Bool
?
这应该有效
var topics:[String:Bool]?
if topics?["Pictures"] == true {
// you have a dictionary
// AND the requested key does exist
// AND its value is true
}
我有时更喜欢的更冗长的成语(视情况而定):
var topics:[String:Bool]?
let topicName="Pictures"
if let topicIsSelected = self.topics?[topicName] where topicIsSelected {
//do stuff
}
更新: 这个的 Swift 3 版本(上面没有在 Swift 3 中编译)读起来不太好:
var topics:[String:Bool]?
let topicName="Pictures"
if let topicIsSelected = self.topics?[topicName], topicIsSelected {
//do stuff
}
如果只想存储一位信息,为什么要使用字典?
只存储一组字符串不是更容易吗?添加您要在字典中存储 true
的所有字符串。然后测试你的字符串是否包含在集合中。
也不需要可选的。只需使用一个空集而不是 nil
.
var topics: Set<String>
...
if topics.contains("Pictures") { ... }
抱歉,当我写完这个问题时,我发现它因为一个愚蠢的语法错误而无法正常工作...我还是发布了这个因为
- 答:我觉得有用
- B:也许大家有更好的主意...
试图让事情变得更优雅......我有一个可选的 [String:Bool]
字典和一个字符串键。现在,在一种情况下我想问:
我有字典吗?
请求的密钥是否存在?
是这个键的值 "true"?
解决方法:
var topics:[String:Bool]?
let topicName="Pictures"
if self.topics?[topicName] ?? false {
//do stuff
}
你为什么使用 Boolean
而不是 Bool
?
这应该有效
var topics:[String:Bool]?
if topics?["Pictures"] == true {
// you have a dictionary
// AND the requested key does exist
// AND its value is true
}
我有时更喜欢的更冗长的成语(视情况而定):
var topics:[String:Bool]?
let topicName="Pictures"
if let topicIsSelected = self.topics?[topicName] where topicIsSelected {
//do stuff
}
更新: 这个的 Swift 3 版本(上面没有在 Swift 3 中编译)读起来不太好:
var topics:[String:Bool]?
let topicName="Pictures"
if let topicIsSelected = self.topics?[topicName], topicIsSelected {
//do stuff
}
如果只想存储一位信息,为什么要使用字典?
只存储一组字符串不是更容易吗?添加您要在字典中存储 true
的所有字符串。然后测试你的字符串是否包含在集合中。
也不需要可选的。只需使用一个空集而不是 nil
.
var topics: Set<String>
...
if topics.contains("Pictures") { ... }