I am currently working on an iOS app which has to parse a URL. The URLs that have to be parsed always have the same format.
Example of such a URL:
myprotocol://label?firstname=John&lastname=Smith
My first thought was to write a "parser" class which is initialised with the String of the URL and has getter methods to return the label
, firstname
and lastname
parsed from the URL.
Pseudocode of such a class:
import Foundation
class URLParser {
var url: URL
init(url: String) {
self.url = URL(string: url)
}
func label() -> String? {
// code to determine label
}
func firstname() -> String? {
// code to determine firstname
}
func firstname() -> String? {
// code to determine lastname
}
}
But then I read more about Swift extensions and saw them being used and recommended in several places.
For my use case I could create an extension for the URL
class that might look like this:
import Foundation
extension URL {
var label: String {
// code to determine label
}
var firstname: String {
// code to determine label
}
var lastname: String {
// code to determine label
}
}
Using an extension like this seems like a good idea on the one hand, because it feels very lightweight and precise. But on the other hand it also feels a bit wrong since the values label
, firstname
and lastname
do not have anything to do with the general idea of a URL. They are specific to my use case.
I would like to clearly communicate in my code what is happening and using classes like MyUseCaseURLParser
or extended classes (inheritance) of URL
called MyUseCaseURL
seem to do that better.
But this is all based on past programming experiences in other languages.
What is the Swifty way of doing something like this and organising the code around it? Are there better ways to do this other than using extensions and classes?