Line of code from Swift to Objective-C

74 views Asked by At

I'm quite blank when it comes to swift, I've been developing using Obj-c. But a tutorial that I've been following uses Swift. Can anyone help me convert the following line of Swift into Objective-C. It's basically to load a String onto an Array.

self.iDArray.append(objectIDs[i].valueForKey("objectId") as! String)
2

There are 2 answers

8
Duncan C On
self.iDArray.append(objectIDs[i].valueForKey("objectId") as! String)

Should be

[self.iDArray append: [objectIDs[1].valueForKey: @"objectID"]]

However, the Swift code is force-casting [objectIDs[1].valueForKey: @"objectID"] to type String (A Swift string).

That suggests to me that self.iDArray may be a Swift array. Swift arrays normally contain only a single type. You create an array of String objects, or an array of Dictionary objects. You can also create an array of AnyObject.

NSArray is an array of id type.

I'm not 100% positive how to force-cast to String type in Objective-C. maybe:

[self.iDArray append: (String) [objectIDs[1] valueForKey: @"objectID"]]
4
danh On

On the surface, objectIDs[x] appears to be a dictionary, and the compiler will give you a break on types if you dereference it that way. So naive to parse, a usable syntax would be:

[self.iDArray append:objectIDs[1][@"objectId"]];

But that's incorrect semantically for parse, since the implication is that the objectIDs array is implied to contain parse objects (named confusingly with the "IDs" suffix). If it's really parse objects, then the collection style reference for objectId won't work, and should be instead

[self.iDArray append:((PFObject *)objectIDs[1]).objectId];

Or more readably:

PFObject *object = objectIDs[1];
NSString *objectId = object.objectId;
[self.iDArray append:objectId];

But, along the same lines semantically, the implication of the code is that it's adding to an NSMutable array, so it probably should be -- for any of the above suggestions:

[self.iDArray addObject: .....

Stop reading here if you care only about compiling and executing without a crash.

But, even if all that's right, which I think can be inferred from the code, it's indicative of bad design in my opinion. Swift developers in particular seem to have a penchant for saving off objectIDs and passing them around as proxies for object, and in so doing, loosing all of the other valuable stuff in the PFObject.

My practice is, wherever possible, just keep and pass the whole PFObject. You can always ask it for its objectId, later. More strongly, my rule of thumb when reading code is: show me parse.com code that refers much to objectIds -- except for things like equality tests -- and I'll show you a design error.