Skip to content

Using a parser in a failable initializer #53

Answered by mbrandonw
adauguet asked this question in Q&A
Discussion options

You must be logged in to vote

In Swift, if you implement an init directly in a struct you lose the automatically (internal) synthesized initializer. So, if you just move your .init?(raw:) to an extension you can get rid of the private init:

struct RegistrationNumber {
    let harbor: Harbor
    let number: String
}
 
extension RegistrationNumber {   
    init?(raw: String) {
        let harbor = Prefix<Substring>(2)
            .map(String.init)
            .compactMap(Harbor.init)
        let number = Prefix<Substring>(6)
            .map(String.init)
        let parser = harbor
            .take(number)
            .skip(End())
            .map { RegistrationNumber(harbor: $0, number: $1) } // ⬅️ Uses the synthesize…

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
4 replies
@adauguet
Comment options

@adauguet
Comment options

@mbrandonw
Comment options

@adauguet
Comment options

Answer selected by adauguet
Comment options

You must be logged in to vote
1 reply
@adauguet
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants