15

What does bridgeToObjectiveC() will do in swift. It seems like converting a Swift object into ObjectiveC object. Is this same as type casting?

For example i can convert a swift String into NSString like

var swingString:String = "test string"
var correspondingNSString = swingString.bridgeToObjectiveC()  // Using bridge

var correspondingNSString = swingString as NSString      // type casting

I want to know both are same or not?

Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
  • the above is the same as String and NSString are toll free bridged – Daij-Djan Jun 04 '14 at 14:50
  • 8
    It's not clear to me that it's appropriate to use the term "toll free bridged" w/r/t swift. That has a very specific meaning w/r/t CoreFoundation and Objective-C. The swift bridging mechanism looks noticeably different to me. – ipmcc Jun 04 '14 at 14:52
  • 1
    @ipmcc the Swift book seems to go out of its way not to use the term where you'd expect them to hit it if it were appropriate (e.g. "Swift's `String` type is bridged seamlessly to Foundation's `NSString` class" in the box out on page 79) so I think your analysis is correct. I guess there is a toll to the bridge, even if its use is seamless, and 'seamlessly bridged' is probably the new appropriate term. – Tommy Jun 04 '14 at 18:22
  • I don't think they're avoiding the term because there's necessarily some unknown "toll". I think they're avoiding the term because "toll free bridging" refers to a very specific mechanism of interaction between CoreFoundation and Objective-C, and swift's mechanism appears to be fundamentally different. – ipmcc Jun 04 '14 at 23:32
  • 1
    Actually, I've had different behavior when converting NSArray and NSDictionaries back and forth using typecasting versus the bridgeToObjectiveC() function. I recommend (for now) using bridgeToObjectiveC() for explicitly bridging obj c and swift objects back and forth. – TheCodingArt Aug 09 '14 at 21:08

1 Answers1

8

My understanding is that bridgeToObjectiveC() is provided so that you don't necessarily need to know what the corresponding objective-c type is; the compiler decides what the appropriate type is.

For example: if you have an array of Any objects can you call bridgeToObjectiveC() on each of them with map without worrying about whether there are String, Int, and Double values.

Using the as keyword allows you to explicitly choose which type you want to cast the value as.

Jiaaro
  • 74,485
  • 42
  • 169
  • 190