Zonily Jame Zonily Jame - 9 months ago 48
Swift Question

Swift struct initialization, making another struct like String

on Swift

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 {

class SomeClass {
let someStringV2:StringV2 = "Hello"

Since that's how
's code looks like.

Answer Source

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 "