convert nsstring to string in swift

To convert an NSString to a Swift String in Swift, you can simply use the String initializer, passing in the NSString instance as an argument. Here's an example:

main.swift
let objectiveCString: NSString = "Hello, world!"
let swiftString = String(objectiveCString)
print(swiftString)
111 chars
4 lines

This will output "Hello, world!" to the console.

Alternatively, you can use the string property of the NSString instance to convert it to a Swift String. Here's an example of that approach:

main.swift
let objectiveCString: NSString = "Hello, world!"
let swiftString = objectiveCString as String
print(swiftString)
113 chars
4 lines

This will also output "Hello, world!" to the console.

Note that when you use the as keyword to convert from an NSString to a String, the conversion is actually performed by a bridging mechanism that is part of the Objective-C runtime. Therefore, using the String initializer may be more semantically clear in your code.

gistlibby LogSnag