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 0×47 to characteristic 0xFFF1.
  • To activate the device’s little blue LED, write 0×01 to 0×1802.
  • 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 0×666666.

  • 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-0×80 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 0×01-0×64 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 0×47 keeps the device from terminating the connection, and the value is reset to 0×01 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?

iBeacon experiments

I’ve wanted to experiment with an actual iBeacon BLE device since iOS 7.0 was released. Whilst there are quite a few companies selling them (e.g. Estimote), they’re all rather expensive for what’s essentially a battery and aerial soldered to about $3 of BLE hardware. However, I recently found an Ebay seller who’d managed to bulk import some of the cheap CC2541-based devices now being made in Shenzhen. For £12 each, I was the proud owner of two.

iBeacon

Although not mentioned by the seller, a little detective work suggests these are the beacons sold by Shenzhen Ankhmaway. If you’re in the mood, you can grab a handful from Alibaba, but you’ll probably have to bulk order, and go through the import rigmarole.

Despite the price, once you’ve put the button battery in, the little guys wake up and start broadcasting a barrage of BLE services that includes the iBeacon advertisement. However, (probably) because of the price, they’re not the best documented devices, and have some strange behaviours. The most obvious is that Bluetooth connections made in the standard way last about 3 seconds before the device terminates them. This is consistent between my code and Lightblue, but *doesn’t* happen to the eBeacon app that a Chinese beacon maker issues. I’m in touch with the seller trying to identify some of the other BTE services the device advertises, in the hope that one can be subscribed/written to as a keep-alive.

Initial impressions:

- The devices can be configured with the eBeacon app, or by writing to the characteristics exported under 0xFFF1-7. The beacon’s proximity ID is in 0xFFF2, the major and minor in 0xFFF3 and 0xFFF4. The others, I’m less sure about. eBeacon suggests they’re transmission power and password management. I’ve no idea what the calibration of the transmission power would be, so that’ll require some guesswork unless the seller comes back to me.
- The beacon does broadcast the standard battery life service, so that’s a plus.
- When a central device is connected to the beacon, it won’t broadcast it’s iBeacon advertisement. As soon as the central device disconnects, the beacon reboots.
- If you want to write to the configuration characteristics, remember to prefix the device password (by default, 0×666666) to the value you want to write. So, to change the beacon’s major identifier, write 0×6666660002 to characteristic 0xFFF3.
- No matter what I do with the beacon, I can’t persuade iOS to see their proximity as anything other than “very close” or “unknown”. However, the accuracy property reported is pretty good at guessing the location, and certainly good enough to deduce relative distances. I’ve no idea yet why the proximity is nonsense.

So, in terms of deducing your devices general proximity to a specific point in space, these guys seem to work exactly as advertised, and for a fraction of the price of the major players. I’ll keep playing, and see what I can do to eradicate the little oddities.