Alex Does Things Poorly

Alex does a variety of things poorly - swift, data science, datavis, ML, drawing, AR, unity, etc, etc.

15 February 2020

Closures, part 2

by alex

Another day of 100 Days of Swift, with more closure confusion this time. Closure syntax is complicated on its own, without even considering all of the shorthand and optional syntactic structures, from trailing closure syntax. The confusion is compounded by the way that the Xcode editor will suggest some shorthand but not others.

This example is stupid and contrived, but whatever.

Given these functions:

func cgContextWatermark(image: UIImage, text: String) -> UIImage {
	let cgImage = image.cgImage
	// .. do the watermarking and return it
}

func watermark(image: UIImage, using algo: (String) -> UIImage) {
    let result = algo("Alex's Photo")
}

These are all valid calling syntaxes. Is there one which is more idiomatic or natural to Swift developers?

watermark(image: myPhoto) { (watermarkText: String) -> UIImage in
    return cgContextWatermark(image: myPhoto, text: watermarkText)
}

watermark(image: myPhoto) { (watermarkText: String) in 
    return cgContextWatermark(image: myPhoto, text: watermarkText)
}

watermark(image: myPhoto) { watermarkText in 
    return cgContextWatermark(image: myPhoto, text: watermarkText)
}

watermark(image: myPhoto) {
    return cgContextWatermark(image: myPhoto, text: $0)
}

watermark(image: myPhoto) { cgContextWatermark(image: myPhoto, text: $0) }

Who knew that syntaxes was the plural of syntax? Not this guy.

Also, you can return a closure from a function, which is pretty nifty:

enum IdentificationTechnique {
    case ComputerVision
    case Jepson
    case Intuition
}

func createIdentifier(using technique: IdentificationTechnique) -> (UIImage) -> String {
    return { _ in 
        switch technique {
        case .ComputerVision: 
            return "It's probably a Western Honey Bee."
        case .Jepson:
            return "Let's key it out."
        case .Intuition:
            return "Definitely a California Slender Salamander."
        }
    }
}

let identifier = createIdentifier(using: .ComputerVision)
let photo = ...
print(identifier(photo))

Finally, my daily annoyance. All the bloggers are whining about iPadOS needing an update, and I’ve mostly been ignoring it. The YouTuber/blogger echo chamber among the Mac/iOS technorati generates mostly garbage; I don’t care about external USB access on my iPad, and I don’t care if anyone agrees with me there. However, there are a few things that are annoying about split view. The safe area isn’t correctly calculated by Playgrounds when in split view, and I’ve seen this in other apps, so I think it’s not just a playgrounds problem. Also, how do I know which view has keyboard focus? When I tap CMD-w on my keyboard, will my playground page or the active safari tab be closed?

tags: