Tuesday, February 6, 2024

Swift Tricks

André Jorgensen:

Generic typealias can be used to simplify param types etc

typealias Parser<A> = (String) -> [(A, String)]


func parse<A>(stringToParse: String, parser: Parser)


Finding Elements of Specific Type in Swift

extension Array {
    func whereType<T>() -> [T] {
        compactMap { $0 as? T } // The function "compactMap(" in Swift is incredibly useful. It maps each element of an array to another optional type and returns the value if it exists (is not null).

I’ve been using a version of this where the type is passed as a parameter. With this version it’s determined using type inference from the call site.

He currently has 202 other tricks listed.

Wade Tregaskis:

for case let rep as NSBitmapImageRep in image.representations {
    … // `rep` is an NSBitmapImageRep.  Non-bitmap reps are skipped.

I sometimes forget that this is possible (and even more often exactly what the damn syntax is – kudos to vacawama in today’s case of this for reminding me with their StackOverflow answer). There are numerous other ways to write the above, but I think it is the most elegant.

I’ve been writing Swift for almost 10 years and still have to think to remember this syntax, as well as if case let. I know that case is for pattern matching, but it still looks weird to see it there, and this is the same reason it’s written using as without the question mark that normally accompanies downcasts that might fail. You might expect to be able to write:

for rep as? NSBitmapImageRep in image.representations {

but instead Swift gives us case let and a more general pattern matching feature. If you write this or get it correct except for the ?, the compiler’s error messages are unhelpful:

for rep as? NSBitmapImageRep in image.representations {
// Expected 'in' after for-each pattern

for case let rep as? NSBitmapImageRep in image.representations {
// Pattern variable binding cannot appear in an expression


Comments RSS · Twitter · Mastodon

Leave a Comment