Swift struct initialization, making another struct

2020-02-07 03:14发布

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条回答
smile是对你的礼貌
2楼-- · 2020-02-07 04:12

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 "
查看更多
登录 后发表回答