Swift 从字典中提取数值

标签 swift dictionary numeric type-conversion

我需要从字典中提取数据(来自 NSXMLParser 的属性,但我认为这并不重要)。下面的方法可行,但这真的是“最简单”的做法吗?该属性可能存在于字典中,也可能不存在。属性的值可能会也可能不会转换为整数(即​​ toInt() 返回一个可选值)。 'mandatory' 是一个 Bool,'minimumLength' 是一个 Int,并且是类属性。

  func decodeDataRestrictions(#attributeDictionary: [NSObject: AnyObject]!) {
var stringValue: String?
var intValue: Int?

// Extract data restrictions from the element attributes
self.mandatory = false
stringValue = attributeDictionary["mandatory"] as String?
if stringValue != nil {
  if stringValue! == "true" {
    self.mandatory = true
  }
}
self.minimumLength = 1
stringValue = attributeDictionary["minimumLength"] as String?
if stringValue != nil {
  intValue = stringValue!.toInt()
  if intValue != nil {
    self.minimumLength = intValue!
  }
}

在 Objective-C 中,这要容易得多:

    self.mandatory = NO;
if ([[attributeDict objectForKey:@"mandatory"] isEqualToString:@"true"]) {
  self.mandatory = YES;
}
self.minimumLength = 1;
if ([attributeDict objectForKey:@"minimumLength"] != nil) {
  self.minimumLength = [NSNumber numberWithInteger:[[attributeDict objectForKey:@"minimumLength"] integerValue]];      
}

最佳答案

您应该能够按如下方式编写整个函数:

func decodeDataRestrictions(#attributeDictionary: [NSObject: AnyObject]!) {

    if (attributeDictionary["mandatory"] as? String) == "true" {
        self.mandatory == true
    }

    if let minimumLength = (attributeDictionary["minimumLength"] as? String)?.toInt() {
            self.minimumLength = minimumLength
    }
}

如果您需要检查可选值是否为 nil,然后使用该值(如果它不为 nil),则 if let 将这两件事结合起来,将局部变量设置为展开的值如果非零。这就是 minimumLength 以及一些可选链接所发生的情况(即,如果该值非 nil,则继续执行 toInt() 否则 nil)。

强制的情况下,您可以使用==将可选值与非可选值进行比较,因此根本不需要检查nil。

编辑:阅读你的 Objective-C 版本后,如果你愿意默认 self 值,即使在缺少字典数据的情况下,你也可以进一步简化它,就像你在那里所做的那样:

func decodeDataRestrictions(#attributeDictionary: [NSObject: AnyObject]!) {

    self.mandatory = (attributeDictionary["mandatory"] as? String) == "true"        
    self.minimumLength = (attributeDictionary["minimumLength"] as? String)?.toInt() ?? 1

}

minimumLength 版本使用 nil-coalescing 运算符,该运算符在左侧为 nil 的情况下替换右侧的默认值。

关于Swift 从字典中提取数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29523277/

相关文章:

MySql 不像正则表达式?

ios - 自定义类别下拉列表中未显示 EDStarRating?

swift - 我无法将图像放入 Swift 5 中的 UIButton

Swift 3 KVO 观察 NSMutableSet 的变化(添加、删除、修改项)

python - Python 中将 (key, value) (key, value) 映射到 (key, (value1, value2))

json - 在 Hive 中分解 json

ios - 让用户画矩形来选择一个区域

vb.net - 无法在字典上使用 LINQ 中的 .Count()

javascript - 如何将 numeric.js 导入我的 javascript 文件

c++ - std::inner_product 计算 vector 的标准差