Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-cloud-platform/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 如何检查字典值是否为布尔值?_Swift - Fatal编程技术网

Swift 如何检查字典值是否为布尔值?

Swift 如何检查字典值是否为布尔值?,swift,Swift,假设我们有这样的东西: static func convertBoolToString(source: [String: AnyObject]) -> [String:AnyObject]? { var destination = [String:AnyObject]() for (key, value) in source { switch value { case is Bool: destination[key] = "\(

假设我们有这样的东西:

  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
的值,它将通过第一个
案例
请检查文件:


如何检查值是否准确且仅为一个
Bool

这是一个棘手的问题。请注意,
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))")
有关其他选项,请参见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
}