Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

xcode - Swift struct initialization, making another struct like String

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 "??")
  • A StringLiteralType (such as String, which is a collection of Characters, such as "This is a string")

Here's an example implementation that just sets a String member variable:

struct StringV2: ExpressibleByStringLiteral {
    let s: String

    init(unicodeScalarLiteral: UnicodeScalar) {
        s = String(unicodeScalarLiteral)
    }

    init(extendedGraphemeClusterLiteral: Character) {
        s = String(extendedGraphemeClusterLiteral)
    }

    init(stringLiteral: String) {
        s = stringLiteral
    }
}

let s1: StringV2 = "This is a string" // String
print(s1.s)

let s2: StringV2 = "A" // Unicode scalar
print(s2.s)

let s3: StringV2 = "??" // Extended grapheme cluster
print(s3.s)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...