我无法将此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”语句中,它告诉我“String不能转换为”MirrorDisposition“。
答案 0 :(得分:2)
你在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()
}
答案 1 :(得分:0)
你看过文档了吗?
func enumerateObjectsUsingBlock(_ block: (AnyObject!,
Int,
UnsafeMutablePointer<ObjCBool>) -> Void)