发送一个枚举,它是字典上的元组并返回

Sending an enum that is a tuple on a dictionary and back

我是Swift的新手,请原谅我的无知。

我有这个枚举:

public enum ConnectionResult {
  case values(state: MCSessionState, peerID:MCPeerID)
}

我把它记在字典里了

let dict = ["values" : ConnectionResult.values(state:state, peerID:peerID)]

我通过通知发送这条口述

NotificationCenter.default.post(name: .adjustState, object: dict)

当我收到通知时,我想获得 statepeerID 值返回

@objc private func onAdjustState(_ notification:Notification) {
  if let dict = notification.object as? Dictionary<String,Any>,
  let result = dict["values"] as? ConnectionResult {

}

如何从结果中获取状态和 peerID?

我试过了

let state = result.values.state as? MCSessionState

我试过了

let (state, peerID) = result  // the thing is a tuple, right?

没有成功...

顺便问一下,有没有办法直接在通知上发送这个 ConnectionResult 对象,即一个元组,而不是使用字典?

ConnectionResult 不是元组。它是一个只有一种情况的枚举(这违背了枚举的目的),因此您需要像处理枚举一样处理它。

得到statepeerID

if case .values(let state, let peerID) = result {
    // you can access "state" and "peerID" here
} else {
    // this will never be reached
}

您可能已经看出来,枚举在这里不合适。我建议更改为实际的元组:

// create the dict like this
let dict = ["values" : (state:state, peerID:peerID)]

// get state and peerID like this
if let result = dict["values"] as? (state: MCSessionState, peerID: MCPeerID) {
    let (state, peerID) = result
} else {
    // handle "dict["values"] as? (state: MCSessionState, peerID: MCPeerID)" being nil
}

struct:

struct ConnectionResult {
    let state: MCSessionState
    let peerID: MCPeerID
}

// create the dict like this
let dict = ["values" : ConnectionResult(state:state, peerID:peerID)]

// get state and peerID like this
if let result = dict["values"] as? ConnectionResult {
    let (state, peerID) = (result.state, result.peerID)
} else {
    // handle "dict["values"] as? ConnectionResult" being nil
}

您也可以直接发送 struct/tuple,而无需先将其放入字典,因为 object 参数接受 Any?。你只需要将 notification.object 直接转换为结构类型或元组类型即可。