4

I use NSKeyedArchiver.archivedDataWithRootObject(obj) to transform an object to NSData. The archivedDataWithRootObject(obj) method require its parameter to be an NSObject, conforming to NSCoding.

I tried archiving Swift Strings, Arrays, and Dictionarys, and it worked well. So I think String is an NSObject conforming to NSCoding.

I also checked this code in a playground, to confirm that String is an NSObject:

var str = "Hello, playground"
let isObject = (str is NSObject) // isObject is true

But when I navigate to String's definition (with Cmd + Click), it shows that String is a struct. I cannot find the code showing that String is an NSObject.

public struct String {
    /// An empty `String`.
    public init()
}

So, why in the String definition, can't I find the code showing that String is an NSObject? And why can a struct be an NSObject?

huynguyen
  • 7,616
  • 5
  • 35
  • 48

1 Answers1

4

String, Array, Dictionary are all bridged to their Objective-C counterparts (NSString, NSArray and NSDictionary) and can seamlessly act like so.

String itself does not inherit from NSObject and is actually a struct but it is bridged from NSString which does. When you use a (Swift) String in your code it can act like an NSString thus giving you the output from the code you provided.

Blake Lockley
  • 2,931
  • 1
  • 17
  • 30
  • Thanks for your explanation. Can you help me how can I create a MyString struct, it bridge to NSString, as swift String struct did? – huynguyen Jul 12 '16 at 04:18
  • 1
    @huync that behaviour is built into the swift language you wont be able to create your own struct and bridge it with NSString... if the reason you want to do is so you can use `NSKeyedArchiver` youre better off simply making a class that inherits from `NSString` or `NSObject` – Blake Lockley Jul 12 '16 at 04:22
  • 1
    @BlakeLockley Any resources to gain knowledge about how how bridging is done between types such as NSString and String? Like the technical process involved in it? +1 though. – Akshansh Thakur Jul 12 '16 at 07:24
  • @AkshanshThakur try these https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-ID35 – Blake Lockley Jul 12 '16 at 08:25