为什么在Objective-C中我可以在块中设置实例变量:
@interface CMVServices : UIViewController
@property (nonatomic, strong) NSMutableArray *times;
@implementation CMVServices
@synthesize times=_times;
and set the _times instance variable inside a block:
(some code )
.
.
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
[_times addObjectsFromArray:objects];
}
但是我不能在斯威夫特?
class ViewController: UIViewController
var times :AnyObject[]!
query.findObjectsInBackgroundWithBlock { (objects: AnyObject[]!, error: NSError!) -> Void in
self.times = objects
}
信息是: (AnyObject []?)次=父无法评估:变量不可用
答案 0 :(得分:2)
两件事:
Array
声明的Swift语法已从AnyObject[]
更改为[AnyObject]
times
代替self.times
。 这适用于Playground文件中的XCode6-Beta4:
import UIKit
class CMVServices : UIViewController {
var times : [AnyObject] = []
func testFunc() {
func findObjects(objects : [AnyObject]!, error : NSError!) {
times = objects
var test_str = "still evaluating in Playground here"
}
findObjects(["test", "string"], nil)
}
}
var test = CMVServices()
test.testFunc()
对于闭包本身的全面测试,这也有效(再次,在XCode6-Beta4中):
import UIKit
class CMVServices : UIViewController {
var times: [AnyObject] = []
func testClosure() {
{ (objects : [AnyObject]!, error : NSError!) -> Void in
self.times = objects
NSLog("still evaluating")
}(["new", "test", "string"], nil)
}
}
var test = CMVServices()
test.testClosure()
test.times // ["new", "test", "string"]