gpt4 book ai didi

Swift 从字典中提取数值

转载 作者:可可西里 更新时间:2023-11-01 01:06:09 25 4
gpt4 key购买 nike

我需要从字典中提取数据(来自 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() else nil)。

mandatory 的情况下,您可以使用 == 将可选值与非可选值进行比较,因此根本不需要检查 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com