2

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!
Jobin Jose
  • 288
  • 2
  • 13
  • Related: http://stackoverflow.com/questions/24006549/calling-nsstring-method-on-a-string-in-swift and http://stackoverflow.com/questions/32638879/swift-strings-and-memory-addresses. Note that the bridging works only if Foundation is imported. – Martin R May 05 '16 at 09:46

2 Answers2

1

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
Code Different
  • 90,614
  • 16
  • 144
  • 163
1

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

Paul Subhajit
  • 142
  • 1
  • 10