Swift访问闭包内的类变量

时间:2014-07-23 15:27:15

标签: variables swift closures

为什么在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 []?)次=父无法评估:变量不可用

1 个答案:

答案 0 :(得分:2)

两件事:

  1. Array声明的Swift语法已从AnyObject[]更改为[AnyObject]
  2. 如果您仍然在班级范围内,只需使用times代替self.times
  3. 这适用于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"]