我希望有人能帮助我。我想用SIOSocket做一个快速的项目。
我正在使用https://github.com/MegaBits/SIOSocket/issues/30中的示例,这个示例似乎很有用,但我希望能够将asocket声明为avar类似于https://github.com/MegaBits/WorldPin中的Objective-C项目示例。所以我可以在代码中调用emit的其他地方使用它。
我假设我不理解Obj-C块和Swift闭包的基本原理,也不理解self的使用,或者不需要将var声明为块,但似乎无法理解它。任何帮助都将不胜感激。
SIOSocket is on Github
目标C代码:

    @property SIOSocket *socket;

    [SIOSocket socketWithHost: @"http://localhost:3000" response: ^(SIOSocket *socket)
{
    self.socket = socket; //I Want to do this in swift

    __weak typeof(self) weakSelf = self;
    self.socket.onConnect = ^()
    {
        weakSelf.socketIsConnected = YES;
        [weakSelf mapView: weakSelf.mapView didUpdateUserLocation: weakSelf.mapView.userLocation];
    };

    [self.socket on: @"join" callback: ^(SIOParameterArray *args)
    {
        [weakSelf mapView: weakSelf.mapView didUpdateUserLocation: weakSelf.mapView.userLocation];
    }];

    [self.socket on: @"update" callback: ^(SIOParameterArray *args)
    {
        NSString *pinData = [args firstObject];

等等…
银行代码:
private func connectToHost() {
    SIOSocket.socketWithHost(host, reconnectAutomatically: true, attemptLimit: 0, withDelay: 1, maximumDelay: 5, timeout: 20, response: {
        socket in

            self.socket = socket // This gives me a use of unresolved identifier self error

            socket.onConnect = {
                println("Connected to \(host)")
                socket.emit("add user", args: [username])
            }

            socket.on("login", callback: {(AnyObject data) -> Void in
                println(["login": data])
                socket.emit("new message", args: [message])
            })

            socket.onDisconnect = {
                println("Disconnected from \(host)")
            }
        })
    }

最佳答案

您的代码应该可以工作,确保您拥有所有正确的类型和可选类型,通过用read-write而不是用var定义socket,确保它是一个let变量。
尝试使用let response: (SIOSocket) -> Void = {...}在方法调用之前定义闭包。

10-08 05:51