Swift talk

I gave a short talk on Swift at the Tunbridge Wells Developer meeting last Tuesday, that seemed to be well received. For posterity, I link the PDF of the slides; a Gist of the Playground is embedded below.

The talk didn’t go into huge detail, as it had to cover a variety of backgrounds. It’s more of a “Why should I care about Swift” tour, detailed interesting languages features that people might not know from elsewhere.

Swift Semantics: Auto-closing over parameters

This post is the second part of a series on the semantics of Swift, Apple’s new programming language. You can see the other posts here as they appear.

One of the most subtle yet most interesting features of Swift is the @auto_closure parameter attribute for functions. Consider the following program:


func someLongCalculation(input : String) -> Int {
    println("I'm calculating \(input)");
    
    return 1;
}

func foo(x : Int, y : Int) -> () {
    // Work with x
    println("I'm working with x!");
    println("Now I'm working with y!");
}


foo(someLongCalculation("One"), someLongCalculation("Two"));

As in most languages, the parameter expressions are evaluated before the function body. Their evaluation order seems to be “implementation defined” at the moment, as does even the fact that they’re evaluated before the function body (the specifications section on “Function Call Expression” does not list anything useful). However, running the above on the current Swift beta, we see

  I'm calculating One
  I'm calculating Two
  I'm working with x!
  Now I'm working with y!

which is probably what we’d expect. Now for the interesting part: we can annotate any parameter as an auto_closure. Auto-closures wrap the given parameter expression up in a closure, and pass that to the function. This allows us to defer evaluation of the argument until it’s actually needed, effectively giving us a form of lazy evaluation! Let’s tweak foo


  func foo(x : Int, y : @auto_closure () -> Int) -> () {
      // Work with x
      println("I'm working with x!");
      let actualY = y();
      println("Now I'm working with y!");
  }

We now see:

  I'm calculating One
  I'm working with x!
  I'm calculating Two
  Now I'm working with y!

Notice that the evaluation of y only happened when we forced it by evaluating the closure.

Auto closures are applicable to any function parameter that you can express with the type () -> ExpressionT (that is, no arguments and returning the type of an expression). With them, we can implement lazy evaluation, call-by-future concurrency semantics, and a variety of exciting operators that act almost like syntax extensions (for example, a short-circuiting boolean OR). This flexibility fuels my prediction that we’ll be seeing a lot of @auto_closures in non-trivial Swift code.

Swift Semantics: for/in

This post is the first part of a series on the semantics of Swift, Apple’s new programming language. You can see the other posts here as they appear.

The Swift language includes a fairly standard “for/inw” statement. Most of the manual introduces it as


  for item in thing {
  }

In this situation, the language asks thing for a generator (via the generate method), then binds each value returned by the generator to thing, before executing the body. However, the general form of for/in is more interesting: rather than just the name thing, we can use a sub-set of the pattern language defined in Swift. The standard example above is using the “identifier pattern”; each value in the generator is bound to the given name. Though I can’t find it explicitally listed in the language reference, it seems any name introduced here is introduced with a let binding.


  for x in [1, 2, 3, 4, 5] {
    println(x)
    // x = 0 // Error: Cannot assign to 'let' value 'x'
  }

Even if the given name already exists, it’s shadowed with a new let bound name.


  for x in [1, 2, 3, 4, 5] {
      println(x)
  }
  println(x) // Still prints "Foo", no type error

In addition to just identifiers, we can use the value-binding, wildcards, and tuples patterns. Value binding allows us to introduce the given name as a variable rather than a constant let:


for (var x) in [1, 2, 3, 4, 5] {
    x = 1
    println(x) // Always prints 1
}

With wildcards, we can throw away the value from the generator. This is probably not generally useful, but does allow us to perform range-bound loops where we don’t care about the index:


for _ in 1...10 {
    println("Hello") // Prints Hello each of the 10 times around the loop
}

Finally, tuple patterns allow us to destuct tuples returned by generators into their components:


for (let x, let y) in [(1, 2), (3, 4), (5, 6)]{
    println(x) // Prints 1, then 3,  then 5
}

Some of the pattern syntax is a bit weird; the use of just “let x” in value-bindings reads strangely without the normally present let x = 5. I might have prefered a different token; const, perhaps. Still, it’s good to see that patterns are spread across the language is a sensible fashion, rather than artificially restricted to switch statements.

Shenzhen Ankhmaway iBeacon characteristics

After yesterday’s post about my cheap Chinese iBeacons, I received some more documentation from the eBay seller, and some excellent information from Rhys Jones of Bookry.com. Between them and my own fiddling, I can now compile a more comprehensive list of services:

  • First, to prevent the devices from disconnecting you after a short window, write 0x47 to characteristic 0xFFF1.
  • To activate the device’s little blue LED, write 0x01 to 0x1802.
  • The battery service is available as normal at 0x180F.

For the following, you’ll need to prefix the password you’ve set onto the values written. It’s three bytes, and the default is 0x666666.

  • To set the proximity UUID, write the password followed by your choices to 0xFFF2
  • To set the major identifier, write the password plus a short to 0xFFF3
  • To set the minor identifier, write the password plus a short to 0xFFF3
  • To set the power value, write the password plus a byte in the range 0xC5-0x80 to 0xFFF4. I’m not sure what the differences between this power and the later Tx power flags are.
  • To change the password, write the old password, plus three bytes of a new password, to 0xFFF6.
  • To set the broadcast rate, write the password plus a value in the range 0x01-0x64 to 0xFFF7. The value changes in 100ms increments.
  • To change the transmission power, write the password plus the two’s-complement of your new power (in dB) to 0x2A07.

When you terminate your connection, the device will restart with the new values. Don’t forget, whilst you’re connected, the device will not broadcast the beacon signal. With these, you should be able to configure your beacons exactly as you want.

iBeacon addendum

After a bit more digging into my Shenzhen Ankhmaway iBeacons – those of the 3 second disconnect – I think I’ve discovered how to prevent the disconnections from central devices. Characteristic 0xFFF1 of service 0xFFF seems to be the keep-alive. Writing the value 0x47 keeps the device from terminating the connection, and the value is reset to 0x01 on disconnection. I’ve not successfully written anything else to this characteristic – other values just terminate my connection. Perhaps this is a basic form of non-password security?