4

Can anyone help to find how to write this in Swift

NSMutableDictionary<FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];

The above ObjectiveC code says objectof type NSMutableDictionary is conform to protocol FBOpenGraphObject. I tried to represent this in swift like

var object:FBOpenGraphObject, Dictionary = FBGraphObject.openGraphActionForPost()

// specify that this Open Graph object will be posted to Facebook
object.provisionedForPost = true   //This will not work

But it is not proper, i'am not able to assign any value to object. Help me to figure out how to represent an object conform to a protocol in swift

Anil Varghese
  • 42,757
  • 9
  • 93
  • 110

1 Answers1

3

Maybe you could do this:

var obj = FBGraphObject.openGraphActionForPost()
if let fbObj = obj as? FBOpenGraphObject {
    // specify that this Open Graph object will be posted to Facebook
    fbObj.provisionedForPost = true // use fbObj for FBOpenGraphObject-specific members
    obj["title"] = "Test hot spot" // use obj for Dictionary-specific members
    // Both obj and fbObj vars point to the same object
}
Romain
  • 3,718
  • 3
  • 32
  • 48
  • This wont work, If I try to do " fbObj["title"] = "Test hot spot"" giving error `FBOpenGraphObject` does not have a member named subscript – Anil Varghese Feb 03 '15 at 06:27
  • This is "expected", as there is no hint to the compiler that the `FBOpenGraphObject` protocol is applied on a `Dictionary` type here. When you want to access `FBOpenGraph`-specific members, use the `fbObj` variable and when you want to access `Dictionary`-specific members, use the `obj` one. I admit there might be a better way that I'm not yet aware of, though. – Romain Feb 03 '15 at 06:38
  • 1
    See also this other SO thread that is similar to your question, and has a similar answer with two different vars pointing the same object but interpreted differently: http://stackoverflow.com/questions/26401778/swift-how-can-i-declare-a-variable-of-a-specific-type-that-conforms-to-one-or-m?lq=1. – Romain Feb 03 '15 at 06:48
  • Thanks for the info. I ll check – Anil Varghese Feb 03 '15 at 07:09