-
I would like to use a parser to validate input and instantiate a type. Since the input may be invalid and the parser fail, this would be a failable initializer. But then, only Can I write this simpler? struct RegistrationNumber {
let harbor: Harbor
let number: String
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) }
if let registrationNumber = parser.parse(raw) {
self = registrationNumber
} else {
return nil
}
}
private init(harbor: Harbor, number: String) {
self.harbor = harbor
self.number = number
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
In Swift, if you implement an 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 synthesized initializer
if let registrationNumber = parser.parse(raw) {
self = registrationNumber
} else {
return nil
}
}
} |
Beta Was this translation helpful? Give feedback.
-
Also, if you are interested, you can make this .map(RegistrationNumber.init(harbor:number:)) |
Beta Was this translation helpful? Give feedback.
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: