【问题标题】:How do I use enumerateObjectsUsingBlock in Swift如何在 Swift 中使用 enumerateObjectsUsingBlock
【发布时间】:2014-12-26 16:04:32
【问题描述】:

我无法将此块代码从 Objective C 转换为 Swift。我在网上搜索了一些示例,但没有解决我得到的错误。

任何帮助将不胜感激。

- (void)didReceiveMemoryWarning {
    [[self.viewControllersByIdentifier allKeys] enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
        if (![self.destinationIdentifier isEqualToString:key]) {
            [self.viewControllersByIdentifier removeObjectForKey:key];
        }
    }];
    [super didReceiveMemoryWarning];
}

这是我尝试过的:

override func didReceiveMemoryWarning() {
    var array : NSArray = self.viewControllersByIdentifier.allKeys
    array.enumerateObjectsUsingBlock { (key, idx, stop) in
        if (![self.destinationIdentifier == key]) {
            self.viewControllersByIdentifier .removeObjectForKey(key)
        }
    }
    super.didReceiveMemoryWarning()
}

我得到的错误是在“if”语句上,它告诉我“String 不能转换为”MirrorDisposition”。

【问题讨论】:

  • 什么错误?你想做什么?你预计会发生什么,实际结果是什么?
  • 您应该将@AirspeedVelocity 标记为“已回答”并提出另一个问题,而不是更改整个问题。现在,问题还不清楚。
  • 感谢您的输入将改变问题。
  • @GoZoner 并不是要更改您的新问题以更好地工作,他的意思是恢复原始文本,将其标记为已回答(假设已回答)并提出一个全新的问题。否则,下面的答案对于其他阅读它们的人来说毫无意义(因为他们正在回答你预先编辑的旧问题)。
  • @AirspeedVelocity 完成!!!谢谢!!!将发布另一个问题。

标签: objective-c swift ios8 objective-c-blocks


【解决方案1】:

你在你的 Swift 中留下了一些 Objective-C(一些流氓方括号):

if(![self.destinationIdentifier == key]) {

但是,您可能会发现使用 Swift 的 for-in 比使用 array.enumerateObjectsUsingBlock 更容易:

override func didReceiveMemoryWarning() {
    for key in self.viewControllersByIdentifier.allKeys {
        // note key will be an AnyObject so you need to cast it to an appropriate type… 
        // also, this means you can use != rather than ! and ==
        if self.destinationIdentifier != key as? NSString {
            self.viewControllersByIdentifier.removeObjectForKey(key)
        }
    }
    super.didReceiveMemoryWarning()
}

【讨论】:

    【解决方案2】:

    你看过文档吗?

    func enumerateObjectsUsingBlock(_ block: (AnyObject!,
                                         Int,
                                         UnsafeMutablePointer<ObjCBool>) -> Void)
    

    【讨论】:

    • 我做到了,我找到了我编辑问题的代码,但仍然出现错误。
    猜你喜欢
    • 2014-08-04
    • 2022-01-12
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多