Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String type a class or a struct? Or something else?

Tags:

swift

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.

like image 637
Ethan Avatar asked Aug 04 '14 05:08

Ethan


People also ask

Is string a class or struct?

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++)??

Is string a class 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.

Can a struct contain a string?

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.

Is a struct the same as a class?

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.


1 Answers

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)
    }
}
like image 167
Bryan Chen Avatar answered Oct 22 '22 10:10

Bryan Chen