Jobin Jose
Jobin Jose

Reputation: 288

How a struct is getting converted as an object using AnyObject in swift

In the following example testString is declared as an object of String which is a struct. But we are able to assign as a object using AnyObject. How the struct to object conversion is happening in swift?

let testString:String = "Hello World" 
let testObject:AnyObject = testString 
print("My test object\(testObject)") // this works!

Upvotes: 2

Views: 89

Answers (2)

Code Different
Code Different

Reputation: 93171

It works because the compiler has special knowledge about String and NSString. String in Swift is bridgeable to NSString in ObjC. You can examine its dynamic type:

let testString:String = "Hello World" 
let testObject:AnyObject = testString 
print("My test object \(testObject.dynamicType)") // object_NSContiguousString

object_NSContiguousString is a private class in the NSString cluster.

Doing so with your own custom struct doesn't work:

struct Person {
    var firstName = ""
    var lastName = ""
}

let testPerson = Person(firstName: "John", lastName: "Smith")
let testObject: AnyObject = testPerson // error

Upvotes: 1

Paul Subhajit
Paul Subhajit

Reputation: 152

Swift and Objective C are not independent. In Swift you can able to use NSString. In your case during compilation an internal bridge is established between testString and converted to NSString type which allows you to store testString into testObject

Upvotes: 1

Related Questions