Swift struct initialization, making another struct

2020-02-07 03:41发布

问题:

on Swift String is a struct and you could just initialize it using

var someString:String = "Hello"

how would I make another Struct initializable like String?

for example

struct StringV2 {
    init()
}

class SomeClass {
    let someStringV2:StringV2 = "Hello"
}

Since that's how String's code looks like.

回答1:

This is (in my opinion) neat part of the language. Yes, this is possible, thanks to the ExpressibleByStringLiteral protocol.

Unfortunately, there is some complexity to it. ExpressibleByStringLiteral inherits from ExpressibleByExtendedGraphemeClusterLiteral, which itself inherits from ExpressibleByUnicodeScalarLiteral. Thus, to conform to the first, you must conform to the other 2 above it.

This makes it possible for your struct or class to be initialized from:

  • A UnicodeScalarLiteralType (such as a UnicodeScalar, which is a single Unicode code point, e.g. "A")
  • An ExtendedGraphemeClusterLiteralType (such as a Character, which is a collection of UnicodeScalars, such as "