Controversial Swift Features
Who would have thought that software development can spawn controversy? Never mind code padding and whethe curly braces should start on a new line, check out these Swift features:
Free For Characters as Identifiers - Swift 6.2
Otherwise known as Raw identifiers.
SE-0451 expands the range of characters one can use to create identifiers – the names of variables, functions, enum cases and similar – as long as these things are placed inside backticks.
This already creates a redability issue, but okay.
The justification for the above goes something like this “Look at our complex enum, now we can parse/write statuses in more readable manner.”
I’m not convinced, to be frank.
enum HTTPError: String {
case `401` = "Unauthorized"
case `404` = "Not Found"
case `500` = "Internal Server Error"
case `502` = "Bad Gateway"
}
And how, you may ask, should one address these cases. Well, like this:
let error = HTTPError.401
switch error {
case HTTPError.401, HTTPError.404:
print("Client error: \(error.rawValue)")
default:
print("Server error: \(error.rawValue)")
}
or alternatively in this manner
switch error {
case .`401`, .`404`:
print("Client error: \(error.rawValue)")
default:
print("Server error: \(error.rawValue)")
}
I just leave it here. 🤷♂️ Not convinced, sorry.
Oh wait, there’s more:
func `function name with spaces`() {
print("Hello, world!")
}
`function name with spaces`()
This reminds me of an old prank. If your colleague left their computer unlocked, you would replace semicolons (;) with Greek question marks (;) and watch the mayhem ensue when they returned.
Method and Initializer Key Paths - Swift 6.2
Slash is used to access “key paths”.
To recap how it works. With the above in place, For example one can extract a single value from each element within any sequence:
let articleIDs = articles.map(\.id)
let articleSources = articles.map(\.source)
Swift 6.2 extends this to support methods alongside the existing support for properties and subscripts.
let uppercased = strings.map(\.uppercased())
print(uppercased)
You have to () (invoke) the method, otherwise you get back an uninvoked function that you can call later on like this:
let functions = strings.map(\.uppercased)
print(functions)
for function in functions {
print(function())
}
While key paths are an undoubtfully useful concept, its implementation using \ is somewhat questionable, as code start approaching redability level or Regex.
Oh and you can’t make key paths to methods that are marked either async or throws.
JavaScriptification Aka Allow trailing comma in comma-separated lists - Swift 6.1
You can now do this:
func add<T: Numeric,>(_ a: T, _ b: T,) -> T {
a + b
}
let result = add(1, 5,)
print(result,)
IMHO it’s just messy, but you do you. 😊