Reputation: 6068
I'm getting this error with the following code:
var dict: Dictionary<String, AnyObject> = [
"peerID": peerID,
"state": state
]
I'm using MultipeerConnectivity
: peerID is of type MCPeerID (e.g., MCPeerID(displayName: "morpheus")
), and state is MCSessionState (an enum, e.g., MCSessionState.Connected
). Apparently, I cannot convert an enum to AnyObject? How can I solve this?
Best.
Edit: I tried using Dictionary<String, Any>, but now I get an exception in the next call. Here's the code:
func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState) {
var dict: Dictionary<String, Any> = [
"peerID": peerID,
"state": state
]
NSNotificationCenter.defaultCenter().postNotificationName(
"MCDidChangeStateNotification",
object: nil,
userInfo: dict
)
}
Xcode indicates the "userInfo: dict" line with the exception:
Thread 10: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Maybe this won't tell you much, so what could I post that would help?
Edit:
By inspecting the object at runtime (after the crash), this is what I get:
state MultipeerConnectivity.MCSessionState Connecting Connecting
dict Swift.Dictionary<Swift.String, protocol<>>
[0] Swift._DictionaryElement<Swift.String, protocol<>>
key Swift.String "state"
core Swift._StringCore
value protocol<>
payload_data_0 Builtin.RawPointer 0x0
payload_data_1 Builtin.RawPointer 0x0
payload_data_2 Builtin.RawPointer 0x0
instance_type Builtin.RawPointer 0x0
There seem to be some null pointers there, but the "state" variable seems fine...
Note: I commented out the peerID assignment.
Upvotes: 1
Views: 3073
Reputation: 33369
Apparently, I cannot convert an enum to AnyObject? How can I solve this?
That's correct, AnyObject cannot contain enums.
I tried using
Dictionary<String, Any>
, but now I get an exception in the next call.
NSNotificationCentre doesn't take a swift Dictionary
, it takes an NSDictionary
.
Wherever possible, Dictionary
and NSDictionary
are inter-operable however NSDictionary
can only have objects as the key and value. You cannot use Any
in a dictionary that needs to be treated as if it were an NSDictionary
by an obj-c API such as NSNotificationCentre
.
So, long story short, a notification userInfo dictionary has to be Dictionary<AnyObject, AnyObject>
(or <String, String>
or something that is an object). You're going to have to use something other than an Enum.
Upvotes: 2
Reputation: 76928
I think you need to use type Any
for the dictionary values (because AnyObject can only be used for an instance of a class):
This worked in a playground for me:
var dict: Dictionary<String, Any> = [
"peerID": peerID,
"state": state
];
Upvotes: 1