huync huync - 4 months ago 8
Swift Question

Are Swift's String, Array, and Dictionary NSObjects? Why can a struct be an NSObject?

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
String
s,
Array
s, and
Dictionary
s, 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
?

Answer

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.