Skip to content

Difference between String and NSString in Swift

String is a struct implemented in Swift Module.

swift
public struct String {
    ...
}
public struct String {
    ...
}

NSString is a class implemented in Foundation Module.

swift
class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
    ...
}
class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
    ...
}

String and NSString instances can be bridged to each other using as operator.

swift
let string = "Hello World"
print(type(of: string))            //"String"
let nsString = string as NSString
print(type(of: nsString))          //"__StringStorage"
let string = "Hello World"
print(type(of: string))            //"String"
let nsString = string as NSString
print(type(of: nsString))          //"__StringStorage"
swift
let nsString: NSString = "Hello World"
print(type(of: nsString))         //"__NSCFString"
let string = nsString as String
print(type(of: string))           //"String"
let nsString: NSString = "Hello World"
print(type(of: nsString))         //"__NSCFString"
let string = nsString as String
print(type(of: string))           //"String"