gpt4 book ai didi

objective-c - 我如何在 Swift 中使用 enumerateObjectsUsingBlock

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

我在将此 block 代码从 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”语句上,它告诉我“字符串不能转换为“MirrorDisposition”。

最佳答案

你在你的 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()
}

关于objective-c - 我如何在 Swift 中使用 enumerateObjectsUsingBlock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27659265/

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