Watched What’s new in Swift. TODO: write simple app(s) in Swift and Objective-C to compare code size and heap usage.

Learned what is Optional Argument Chaining. I have known what it is, but did not know the name.

// Reading contents of URL might look like this:
let contents: String?
if let url = URL(string: "/url/to/image") {
	contents = try? String(contentsOf: url)
 } else {
 	contents = nil
 }

 // or like this with optional argument chaining:
 let contents1 = try? URL(string: "/url/to/image").flatMap(String.init(contentsOf:))

 

let image: UIImage?
if let url = URL(string: "https://apple.com/favicon.ico"),
   let data = try? Data(contentsOf: url)
{
    image = UIImage(data: data)
} else {
    image = nil
}

// alternative with optional chaining:
let image1 = URL(string: "https://apple.com/favicon.ico")
             .flatMap{ try? Data(contentsOf: $0) }
             .map(UIImage.init(data:))
// flatMap usage is like that because otherwise compiler is not smart enough to use `Data(contentsOf:options)`
// with default second parameter.

 

TODO: write to swift forums question if this could be emproved in Swift.