是否有可能推广和/或简化这两个“计算属性”

时间:2015-03-27 13:28:17

标签: ios swift notifications closures block

我有一个快速的项目,我正在使用通知来传递数据。当我发布通知时,我在消息中编码["data" : data ]

data属于ParsedMessage类型,其中有多个子类型。

当我收到通知时,我正在使用块样式方法来处理通知。我这样做是因为我想尽量避免拼写错误或忘记在选择器方法末尾添加:的问题。我开始认为如果我使用选择器,我最终会得到更清晰的代码但是因为我正在探索一些快速的funkiness,我想至少尝试这条路线。

所以在任何情况下我都有两个块来处理子类ParsedMessage的数据,即AHRSMessageLocationMessage

// Define a block to be called by the notification center
lazy var ahrsDataHandler : notificationBlock = { notification in

    if let d : Dictionary = notification?.userInfo,
        msg : AHRSMessage = d["data"] as? AHRSMessage
    {

        println (msg.roll)

        self.expectation1!.fulfill()
    } else {
        println("\(__FILE__)::\(__LINE__)Could not parse AHRS Data correctly")
    }

}

// Define a block to be called by the notification center
lazy var locationDataHandlerBlock : notificationBlock = { notification in

    if let d : Dictionary = notification?.userInfo,
        msg : LocationMessage = d["data"] as? LocationMessage
    {
        println("Latitude: \(msg.lat)")

        self.expectation1!.fulfill()
    } else {
        println("\(__FILE__)::\(__LINE__)Could not parse Location Data correctly")
    }

}

最终将这两个计算属性传递给对:

的调用 需要阻止的

addObserverForName(...)

有没有办法使用泛型和/或我错过的东西来简化这段代码?

调用if let d : Dictionary = notification?.userInfo, msg : AHRSMessage = d["data"] as? AHRSMessage似乎有点不合情理

我想知道是否有一些函数可以构造我可以传递一个闭包和一个类型或什么东西,它会在这里“生成”一个类似于我创建的块。

func generateNotificationBlock<LocationMessage>()或其他什么,但我最终让自己感到困惑。

由于

1 个答案:

答案 0 :(得分:-1)

所以我走了另一个方向,对Notifications进行了类扩展,效果很好!

/**
These class extensions make it easier to work with Notificationss
*/
extension NSNotification {


    /**
    If the notificaiton has a UserInfo field that is equal to ["data" : AHRSMessage ], this function
    wiill extract the Location message otherwise it will return nil

    :returns: userInfo["data"] extracted as a AHRSMessage
    */
     var asAHRSMessage : AHRSMessage? {
        get { return self.asParsedMessage() }
    }


    /**
    If the notificaiton has a UserInfo field that is equal to ["data" : LocationMessage ], this function
    wiill extract the Location message otherwise it will return nil

    :returns: userInfo["data"] extracted as a LocationMessage
    */
     var asLocationMessage : LocationMessage? {
        get {
            return self.asParsedMessage()
        }
    }

    /**
    If the notificaiton has a UserInfo field that is equal to ["data" : ParsedMessage ], this function
    wiill extract the Location message otherwise it will return nil

    :returns: userInfo["data"] extracted as a ParsedMessage
    */
    private func asParsedMessage<T>() -> T? {
        if let d : Dictionary = self.userInfo,
            msg : T = d["data"] as? T
        {
            return msg
        }
        return nil
    }
}