class MyString: String {}
gives an error:
Inheritance from non-protocol, non-class type \'String\'`.
S
If you command+click String in Xcode
struct String {
init()
}
So String is a struct.
You can't subclass from struct as the error message said:
error: Inheritance from non-protocol, non-class type 'String'
However, you can implicitly convert it to NSString (which is subtype of AnyObject) only if you have imported Foundation directly or indirectly.
From REPL
1> var str = "This is Swift String"
str: String = "This is Swift String"
2> var anyObj : AnyObject = str
.../expr.oXbYls.swift:2:26: error: type 'String' does not conform to protocol 'AnyObject'
var anyObj : AnyObject = str
^
1> import Foundation // <---- always imported in any useful application
2> var str = "This is Swift String"
str: String = "This is Swift String"
3> var anyObj : AnyObject = str
anyObj: _NSContiguousString = "This is Swift String" // it is not Swift string anymore
4>
But try to avoid to subclass String or NSString unless you absolute have to. You can read more at NSString Subclassing Notes.
Use extension to add new method to String
extension String {
func print() {
println(self);
}
}
"test".print()
Use delegation pattern if you want to have more control over it
struct MyString {
let str : String = ""
func print() {
println(str)
}
}