Archive for July, 2015

Swift: Did something change with implicit unwrapping when I wasn’t looking?

Book

Screen Shot 2015-07-17 at 9.29.05 AM

Reality

Screen Shot 2015-07-17 at 9.29.22 AM

What I expected was:

Also tested in compiled app, with same (non-crashing) behavior. Any insight? Anyone? Anyone? Bueller?

Update:

David Owens writes:

Sure enough:

Screen Shot 2015-07-17 at 9.35.06 AM

Thanks!

And finally, word of Jordan:

 

Swift: Ad hoc anonymous arguments

The other day, I posted the following snippet to demonstrate string regex:

"Hello".rangeOfString("l{2}",
    options: [.RegularExpressionSearch],
    range: "Hello".startIndex..<"Hello".endIndex,
    locale: nil)

This code is clunky for various reasons, not the least of which is that I had to type “Hello” three times. There already exists a Swift mechanism for cleaning this up using closures and anonymous arguments. Here’s what that looks like:

let range = {
    $0.rangeOfString("l{2}",
        options: [.RegularExpressionSearch],
        range: $0.startIndex..<$0.endIndex,
        locale: nil)
}("Hello")

I’m not a fan of the trailing arguments. The intent is hard to read.

I should mention that the let range assignment is required. Without it, Swift complains of trailing closures:

// Trailing closure error for whatever precedes this line
{
    $0.rangeOfString("l{2}",
        options: [.RegularExpressionSearch],
        range: $0.startIndex..<$0.endIndex,
        locale: nil)
}("Hello")

Anonymous arguments are also required. You cannot use label binding. The following code errors because string is used before it’s defined.

// Error error: use of unresolved identifier 'string'
let range = {
    string.rangeOfString("l{2}",
        options: [.RegularExpressionSearch],
        range: string.startIndex..<string.endIndex,
        locale: nil)
 }(string: "Hello")

Of course, you can work around anonymous arguments by declaring string within the closure. You can see how this is already losing the “simplicity win” I was going for.

// Thanks BigO and Ketzusaka
let range = { string in
    string.rangeOfString("l{2}",
    options: [.RegularExpressionSearch],
    range: string.startIndex..<string.endIndex,
    locale: nil)
 }("Hello")

It would, of course, be nice to have some sort of do work-around like the following to avoid the naked scope error.

do {
    $0.rangeOfString("l{2}",
        options: [.RegularExpressionSearch],
        range: $0.startIndex..<$0.endIndex,
        locale: nil)
}("Hello")

Even here, I’m not a huge fan of the postfix argument. Seems to me that something like do(arguments){} or with(arguments){} would be nicer than do{block}(arguments).

While I’m rambling, let me add one more complaint. I’ve been missing and wanting closure-specific state because

var n = 0; var naturalNumbers = anyGenerator{return n++}

seems less natural (no pun intended) than

var naturalNumbers = anyGenerator{static n = 0; return n++}

What do you think? Drop a comment, a tweet, email.

Dear Erica: How do I perform regular expression search in Swift strings?

Depends on Foundation. I don’t love it but here you go.

"Hello".rangeOfString("l{2}", 
    options: [.RegularExpressionSearch], 
    range: "Hello".startIndex..<"Hello".endIndex, 
    locale: nil)

infix operator ~== {}
func ~==(lhs: String, rhs: String) -> Range<String.Index>? {
    return lhs.rangeOfString(rhs, 
        options: [.RegularExpressionSearch], 
        range: lhs.startIndex..<lhs.endIndex, 
        locale: nil)
}

"Hello" ~== "l{2}" // 2..<4

Thanks, Quark67 for catching typo

Well, lookie that! A new iPod touch!

Screen Shot 2015-07-15 at 12.18.32 PM

Just when you thought they went extinct:

CUPERTINO, California — July 15, 2015 — Apple® today introduced the best iPod touch® yet and unveiled a new lineup of colors for all iPod® models, including space gray, silver, gold, pink and blue. The ultra-portable iPod touch features a new 8 megapixel iSight® camera for beautiful photos, an improved FaceTime® HD camera for even better selfies, the Apple-designed A8 chip with 10 times faster graphics performance for a more immersive gaming experience, and even better fitness tracking with the M8 motion coprocessor

We own an iPod touch 5th gen that I picked up refurb for about $150 and it’s really fabulous. One of my favorite iOS purchases ever, and currently my primary development unit for iOS 9.

The new iPods with teen-friendly case colors (think metallic rather than iPhone 5C colored, plus the now-standard gold/silver/black) start from $199 at the Apple Store.

Both the nano and the shuffle also appear to include new finishes.

New to the Internet of Things: Eddystone BLE Info transmissions

From Google:

Move over iBeacon–today Google is launching “Eddystone,” an open source, cross-platform Bluetooth LE beacon format. Bluetooth beacons are part of the Internet of Things (IoT) trend…Like iBeacon, but more open.

Interestingly enough, the press release includes “Kulick told Ars,” which strikes me as a really odd phrase to include in a press release that’s not actually from Ars Technica. (Waves hi to Jacqui.)

Details here. Color me intrigued.

Swift: Just because

struct Pt {
    let x: Int
    let y: Int
    init(_ x: Int, _ y: Int) {self.x = x; self.y = y}
    init(){self.init(0, 0)}
}

let p = Pt(2, 3)

func valueForKey(item : Any, key: String) -> Any? {
    let mirror = reflect(item)
    for index in 0..<mirror.count {
        let child = mirror[index]
        if key == child.0 {return child.1.value}
    }
    return nil
}

valueForKey(p, key: "x") // 2
valueForKey(p, key: "y") // 3
valueForKey(p, key: "z") // nil

Swift: Updating optionals

I previously wrote about optionals way back in June 2014, so as I’m working on the book, it’s giving me a good opportunity to look back and compare then and now.

From 1.x to 2.0, we had if let pyramids of doom (too much indent) leading to variable binding constipation blocks (too much condensed reading), and now the yeoman of the guard patterns (too much error handling overhead). Things keep getting better, but I’m not convinced we’re there there yet.

Read On…

Swift: Enumerations or how to annoy Tom

In the dark fetid implementation mists behind the slick city Swift streets lies a secret world where enumerations are merely ints with pretensions. In more objective terms, Swift enums provide a complete and finite ordered listing of the possible members in a fixed collection. They basically come in three flavors.

Read On…