class MyString: String {}
gives an error:
Inheritance from non-protocol, non-class type 'String'`.
So looks like String
is not a class. But why it can be used in context where AnyObject
is expected? I though AnyObject
is for class type only, while Any
could be a class or non-class type.
Since it is class type (i.e. not a struct), String copy should also contain Empty because the = operator in C# assigns reference of objects rather than the object itself (as in C++)??
A string is not a data type but a class in System namespace in C# i.e., System. String and string is an alias (another name) of the same.
The answer is yes unless you are using an obsolete compiler that does not support initialization of structures with string class members. Make sure that the structure definition has access to the std namespace. You can do this by moving the using directive so that it is above the structure definition.
Classes and Structs (C++)The two constructs are identical in C++ except that in structs the default accessibility is public, whereas in classes the default is private. Classes and structs are the constructs whereby you define your own types.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With