假设我们有这样的事情:
static func convertBoolToString(source: [String: AnyObject]) -> [String:AnyObject]? {
var destination = [String:AnyObject]()
for (key, value) in source {
switch value {
case is Bool:
destination[key] = "\(value as! Bool)"
default:
destination[key] = value
}
}
if destination.isEmpty {
return nil
}
return destination
}
问题在于,如果值为Double
或Int
或任何可转换为Bool
的内容,则会传递第一个case
。
请检查文档:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html
如何确切地检查值,只检查Bool
?
答案 0 :(得分:2)
这是一个棘手的问题。请注意,Bool
,Double
或Int
都不是AnyObject
,它们都是值类型。这意味着它们在字典中表示为NSNumber
。但是,NSNumber
可以将其保留的任何值转换为Bool
。
检查NSNumber
内的类型并不容易。检查的一种方法是将引用与NSNumber(bool:)
构造函数的结果进行比较,因为NSNumber
始终返回相同的实例:
func convertBoolToString(source: [String: AnyObject]) -> [String:AnyObject]? {
var destination = [String:AnyObject]()
let theTrue = NSNumber(bool: true)
let theFalse = NSNumber(bool: false)
for (key, value) in source {
switch value {
case let x where x === theTrue || x === theFalse:
destination[key] = "\(value as! Bool)"
default:
destination[key] = "not a bool"
}
}
if destination.isEmpty {
return nil
}
return destination
}
let dictionary: [String: AnyObject] = ["testA": true, "testB": 0, "testC": NSNumber(bool: true)]
print("Converted: \(convertBoolToString(dictionary))")
有关其他选项,请参阅get type of NSNumber
答案 1 :(得分:1)
Swift 3版本:
static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? {
guard let source = source else {
return nil
}
var destination = [String:Any]()
let theTrue = NSNumber(value: true)
let theFalse = NSNumber(value: false)
for (key, value) in source {
switch value {
case let x as NSNumber where x === theTrue || x === theFalse:
destination[key] = "\(x.boolValue)"
default:
destination[key] = value
}
}
return destination
}