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

后端 未结 1 364
悲哀的现实
悲哀的现实 2021-01-04 03:03
class MyString: String {}

gives an error:

Inheritance from non-protocol, non-class type \'String\'`.

S

相关标签:
1条回答
  • 2021-01-04 03:42

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题