Home > Net >  Swift - Why CFString and NSString are assignable?
Swift - Why CFString and NSString are assignable?

Time:10-05

I'm trying to understand the magic. Why are some types assignable? Is that because of any declarations in the code, or are those relations hidden from us?

I've made a simple function that is compilable:

func convert(_ x: CFString) -> NSString { x }

However, when I'm trying to do the same with the String type, it doesn't work. Only the following code is compilable:

func convert(_ x: CFString) -> String { x as String }

The declaration of the class is empty:

public class CFString {
}
public class CFMutableString : CFString {
}

So how it understands that these types could be assigned to each other? How do I find the whole list of such types?

CodePudding user response:

CFString and NSString are toll free bridged within Objective C.

https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html

String is Swift. It is bridged to NSString but not to CFString. But you can cast.

  • Related