Archive for May, 2017

Erica Knows Nothing About Kotlin: Kotlin functions

Yesterday, I got my feet wet creating a simple functional chain to calculate the sum of natural numbers that are multiples of 3 or 5 (thanks Jeff):

var result = (1 .. limit - 1)
    .asSequence()
    .filter { item -> item.divisibleBy(3) || item.divisibleBy(5) }
    .sum()

As you can see, Kotlin looks a lot like Swift. And, like any programming language, you can collect a routine into a function (fun rather than func in Kotlin, which makes Kotlin seem like a very “happy fun™” language) for re-use.

Instead of using a temporary result variable (var, just like in Swift, although let is val) and re-assigning it at each calculation, it’s more elegant to create a reusable component to call for each limit.

The simplest way is to build a function that mimics Swift. You declare fun, the function name, parameters, the return type (with a : token), and use the return keyword to establish the return value:

fun Int.divisibleBy(factor: Int) = this % factor == 0

fun euler1 (limit: Int) : Int {
    return (1 .. limit - 1)
        .asSequence()
        .filter { item -> item.divisibleBy(3) ||item.divisibleBy(5) }
        .sum()
}
println("The sum of these multiples is ${euler1(10)}")
println("The sum of these multiples is ${euler1(1000)}")

I also munged the calls directly into the print string using ${}. This is basically the same as using \() in Swift. The new  euler1 function is now almost indistinguishable from Swift.

Kotlin offers a bit more flexibility in its function declarations. You can skip the braces and use assignment to the compound expression, creating an inferred scope for short expressions:

fun euler1 (limit: Int) : Int = (1 .. limit - 1)
        .asSequence()
        .filter { item -> item.divisibleBy(3) ||item.divisibleBy(5) }
        .sum()

Same results, much streamlined declaration.

Like Swift, you can introduce defaulted arguments into your parameter list. This example can be called with zero or one arguments, allowing the printed phrase to default to “Hello World”.

fun greet(phrase: String = "Hello World") = println(phrase)
greet() // "Hello World"
greet("Hello Sailor") // "Hello Sailor"

You can also create functional closures/lambda expressions and assign them to variables, as you do in Swift. And, as in Swift, that closure can then be treated like a normal function:

var add : (Int, Int) -> Int = {item, increase -> item + increase }
println(add) // Function2<java.lang.Integer, java.lang.Integer, java.lang.Integer>
println(add(2, 3)) // 5

Finally, like Swift, you can create infix functionality, such as exponentiation. The first two examples use the infix form, the second two use a standard function call:

infix fun Int.exp(exponent: Int): Int {
    return (1 .. exponent)
        .asSequence().map { this }
        .fold(1) {current, base -> current * base }
}

println(5 exp 3) // 125
println(2 exp 8) // 256
println(5.exp(3)) // 125
println(2.exp(8)) // 256

Erica Knows Nothing About Kotlin: Installing and using Kotlin from Xcode

Andy Wilkinson wanted some useful tips for Kotlin in the style of my normal blog. I know nothing about Kotlin other than it’s vaguely Swifty and has a little too much Java in it for my decaf tastes. Nonetheless, I decided to oblige.

Here’s what I discovered.

Install Kotlin

Installation couldn’t be simpler. I used brew: brew install kotlin, which installed a copy to /usr/local/bin/kotlin on my first try. Woo!

Say “Hello World”

You run the Kotlin REPL with kotlinc-jvm, which I did not guess on my first try and had to hunt around doing web searches to discover:

Next, I tried to create an app. Once again I discovered that Kotlin is a little less straightforward than Swift in this regard.

Notice that you have to call kotlinc, the command line compiler, not kotlin. Then you can run the  736709-byte large jar results with (ew) java.

Unfortunately, it’s not as simple as one might hope to create a straightforward script:

However if you rename the file from hello2.kt to hello2.kts, you can run it as a command-line script:

Whee.

Hop into Xcode

Create a new Cross-platform Xcode project: File > New > Project > Cross-platform > External Build System > Next. Enter a name, and edit the build tool to kotlinc. Click Next. Navigate to a save location and click Create.

Choose File > New > macOS > Other > Empty. Click Next. Name the file HelloWorld.kts. (See the kts extension? This allows it to be run as a script.)

Edit your Run scheme (Scheme > Edit Scheme or Command-<). Choose the Info tab, select Other from the Executable pop-up list.

Type a forward slash, then continue to navigate to /usr/local/bin. Select kotlinc, uncheck Debug executable, and then click Close.

Next choose the Arguments tab and edit the arguments passed on launch to include both the -script flag and the source file:

You’re now ready to run:

Do something interesting

Now that you have the basics all ready to play with, create a slightly more interesting testing environment. For example, pull up Project Euler and challenge yourself to a few of their ideas:

That Kotlin “Feeling”

As when I played around with Python, I was surprised at Kotlin’s familiarity.

  • The println commands felt quaint and old fashioned like Swift 1.
  • The cascading dot sequence (which I cut and pasted for the second result, and Xcode didn’t automatically indent) felt as fresh as modern Swift. I also felt pretty confident in my overall Swift-influenced style despite jumping into an entirely new language.
  • Extending Int with the divisibleBy function was a little weird and I deliberately used the = syntax to define my function rather than a more familiar brace and return, just so I could say I tried to be more authentically kotlinny.
  • The two dot range did catch me but it was an easy fix from three dots to two.
  • I quite liked using $-delimited variable names compared to Swift’s \() insertion sequence.

Given that other than a few math functions and hello world, this post contains all my Kotlin code to date, I don’t have much more to add about the language similarities and differences, but let me know if you’d be interested in reading more about “Erica learns Kotlin”. Otherwise, I’ll get back to doing other things during this extremely dead week before WWDC starts.

In praise of Tile trackers

A friend (hi Charles!) sent me a couple of Tile products (one “slim” for my wallet, one “mate” for my keys) to test out. Like other tracking products on the market, you attach a tile to your belongings, register and name it with the app.

When you lose sight of your belongings, use the app to track it down. You can play a sound to help you find where in your backpack or purse it’s gotten to or use the app to find where it’s gone to on a map.

I’ve used and reviewed similar products in the past. Despite (and possibly because of) Tile’s “no self-service” design, it has provided the best user experience to date. The unit is small, easy to attach to things (the “mate” has a built-in hole), and extremely light.

Like other trackers, Tile uses crowdfinding to notify you when your tile shows up after it goes missing.

If your item isn’t where you last had it, select “Notify When Found” in the app and when any device in the Tile community simply passes by your missing item, you’ll automatically be notified of its most recent location. This feature works 100% anonymously and automatically to protect your privacy.

Over the weekend, my son and I visited a very large park. I slipped my keys into his backpack and used my app to keep an eye on how far ahead of me he had biked. He enjoyed his ride without constant “mom nag” but with a certain peace of mind for me. (Update: No, this would not have worked at a state park, you’d need a phone with GPS for that, but it was fine at an inner city park with lots of phones accompanying bikers, joggers, dog walkers, etc.)

For the most part, thankfully, I haven’t needed to use the Tile or its app. For the few times when I’ve needed it, it’s been right there for both  keychain and wallet, reducing my anxiety and making it easy to find my stuff.

Tile Mate and Slim cost $25 and $30 for a one pack, with discounts as you buy in quantity. You can purchase adhesive tape (for remote controls), iron-on pockets (for jackets), and zip straps (for your bike) to secure more items than just keys and wallets.

The batteries are guaranteed for a year, then you can “reTile” at a discounted price ($12/Tile original, $15/Tile mate, $21/Tile slim).

Yes, Tile is not cheap (especially if you buy single units) but I’ve been extremely impressed by the reliability, ease of use, and the accompanying application.

Tests that don’t crash

Give a big hi to Tim V! He’ll be posting here when a topic inspires him and today, he’s going to talk about how to write tests that fail gracefully.

Most people that have been writing Swift code for a while try to limit their usage of optional force unwraps and try! as much as possible. Test code, on the other hand, is often still littered with unsafe code. It’s true that crashes in tests aren’t nearly as undesirable as in production code, but it’s fairly straight-forward to write tests that fail gracefully when an unexpected nil is encountered, or when an error is thrown unexpectedly.

Consider the following unit tests:

class Tests: XCTestCase {
    func testFoo() {
        let value = try! foo()
        XCTAssertEqual(value, 5)
    }
    
    func testBar() {
        let value = bar()!
        XCTAssertEqual(value, "bar")
    }
}

What a lot of people don’t seem to know is that individual tests can be marked with throws to automatically handle thrown errors:

func testFoo() throws {
    let value = try foo()
    XCTAssertEqual(value, 5)
}

Much better. To write testBar in a safer way, we’ll need to throw an error when the output of bar is nil. We could declare a separate error for each optional value we want to unwrap in one of our tests, but that requires writing a lot of extra code. Instead, we can throw a more general Optional.Error.unexpectedNil each time an unexpected nil value is encountered:

extension Optional {
    enum Error: Swift.Error {
        case unexpectedNil
    }
    
    func unwrap() throws -> Wrapped {
        guard let value = self else { throw Error.unexpectedNil }
        return value
    }
}

Note: Swift 3.0 and below does not support nesting types inside a generic type, so if you’re not yet using Swift 3.1, you’ll have to declare a separate enum OptionalError instead.

Now we can rewrite testBar as follows:

func testBar() throws {
    let value = try bar().unwrap()
    XCTAssertEqual(value, "bar")
}

After these changes, whenever a test would normally crash, it now simply fails. And as a bonus, all tests are guaranteed to be executed, where previously a single crash would prevent the remaining tests from being run.

5 Easy Dispatch Tricks

Swift Dispatch offers a great way to schedule and control concurrent code. Here are five easy ways to improve your Dispatch experience.

1. Adding Seconds

Swift makes it easy to fetch the current time as DispatchTime.

let timeNow = DispatchTime.now()

You can easily add seconds to now (in Double increments) using the + operator. As you can see from its signature, the RHS of the + operator expects a Double value of seconds.

Here are a couple of examples that show how easy it is to do this:

let timeInFive = DispatchTime.now() + 5
let timeInSevenAndHalf: DispatchTime = .now() + 7.5

DispatchTime also supports the minus operator, although subtraction is rarely used in dispatch:

public func -(time: DispatchTime, seconds: Double) -> DispatchTime

2. Adding unit time

DispatchTimeInterval offers handy units for microseconds, milliseconds, nanoseconds, and seconds. They all take integer arguments:

For example, you might dispatch five print commands, each offset by an increasing number of seconds:

(1 ... 5).forEach {
    DispatchQueue.main.asyncAfter(
        deadline: .now() + .seconds($0)) {
        print("Hi there!")
    }
}

This approach works by mixing and matching DispatchTime and DispatchTimeInterval math. These operators, too, are baked into Swift:

public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime
public func -(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime

This version is arguably more readable and maintainable than the raw + 5 from trick #1:

let timeInFive = DispatchTime.now() + .seconds(5)

3. Going Floating Point with Dispatch Time Intervals

DispatchTimeInterval case initializers are limited to integer arguments. You can extend the type to add support for double values, returning a nanosecond instance with the equivalent value for a Double number of seconds:

// Built-in enumeration
public enum DispatchTimeInterval {
 case seconds(Int)
 case milliseconds(Int)
 case microseconds(Int)
 case nanoseconds(Int)
}

// Custom factory using a `Double` value
extension DispatchTimeInterval {
    public static func seconds(_ amount: Double) -> DispatchTimeInterval {
        let delay = Double(NSEC_PER_SEC) * amount
        return DispatchTimeInterval.nanoseconds(Int(delay))
    }
}

Like the earlier use of DispatchTimeInterval this convenience constructor improves code readability while bypasssing Int-only case initializers:

let timeInEightAndHalf: DispatchTime = .now() + .seconds(8.5)

4. Async Forwards

Although DispatchTime math is convenient, it’s super-common to schedule code with respect to the current time. Why not let DispatchTime do the heavy lifting for you? Instead of saying .now() + some interval, consider extending DispatchTime to  incorporate now into the call. Here’s an example that introduces a secondsFromNow(_:) dispatch time:

extension DispatchTime {
    public static func secondsFromNow(_ amount: Double) -> DispatchTime {
        return DispatchTime.now() + amount
    }
}

stride(from: 1.0, through: 5.0, by: 1.0).forEach {
    DispatchQueue.main.asyncAfter(deadline: .secondsFromNow($0)) {
        print("Hi there!")
    }
}

5. Testing in Playgrounds

When working with dispatch in Playgrounds, ensure that execution  continues until your work is done. Use PlaygroundPage‘s indefinite execution and halting to control that work.

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(10)) {
    print("Ending Execution")
    PlaygroundPage.current.finishExecution()
}

Got any other favorite dispatch tricks? See something I need to fix? Drop me a comment, a tweet, or an email and let me know.

Update:

Like this post? Consider buying a book. Thank you!

Randomness and Portability

If you’ve written cross-platform code between Apple and Linux, you may have run into the “missing arc4random” issue. Part of BSD, and therefore automatically distributed with Darwinarc4random uses “the key stream generator employed by the arc4 cipher, which uses 8*8 8 bit S-Boxes”

On Linux, you can revert back to rand()/random() using conditional compilation but that’s not a great solution for anyone looking for quality pseudo-randomness. Matt Gallagher has a lovely write-up about native Swift RNGs at Cocoa with Love, and links to his implementation over at the CwlUtils repository.

Jens Persson, on the swift-users list, offers this native Swift generator,  a “stripped down version” of Xoroshiro128+ PRNG as well.

When Engineers Design Apps

When engineers design apps, they get this:

I know because I’ve been there. I have the design talent of three-day old roadkill.

When engineers let their family members help out with design, they get this:

It may not win Apple design awards but it’s charming, bright, and engaging.

Congrats to Chris & Mrs. Chris on the UI and the application (App Store link).

Update: Dave Sweeris tweeted: “I’d love to see a before & after where an app was completely finished solely by engineers, and then UI experts when back and redid the UI…I bet both “sides” would learn something. If nothing else, the write-up would make an interesting article.”

Here’s a side-by-side video from a few years ago you might enjoy:

Xcode Autocomplete Frustrations

A year after it debuted, Xcode’s enhanced autocomplete features continue to struggle with overly liberal matches:

In this example, several of the matching text results display few commonalities with my search phrase . There’s really no reason that “fatale” should match CFDataGetLength(theData: CFData!).

It shouldn’t be hard to create heuristics that count the number of matched chunks, their distance from each other, to build a score related to whether the match is chunky (a good thing for keywords) and singular (another good thing for discerning developer intent).

Successful autocompletion promotes good matches and discards inappropriate ones. “upper” should score high on CFStringUppercase and low on CGScreenUpdateOperation and CSSMERR_TP_INVALID_CERTGROUP_POINTER.

That’s not the only problem with autocomplete. Image literal completion is a big problem. Xcode often prioritizes images over code APIs. When starting to type “picker”, Xcode should not suggest “picture-of-lovely-cat”. Here are some real world examples of this issue:

One developer told me that while typing in for closures, that eighty percent of the time, he gets a random autocompleted image literal instead of the keyword he’s shooting for:

Surely, this is an obvious place to introduce autocomplete preferences that allow you to exclude literals from the API list. The auto complete for image literals should act more like colors, offering an Image Literal entry point to a image picker instead of clogging the API name space:

It would certainly get rid of those inappropriate in matches.

Thanks Olivier Halligon, Andrew Campoli, and everyone else who gave me feedback and direction for this post.

Fun with Unicode Names

I don’t use Unicode all that often but I tend to use the character picker copypasta or hex codes when I do:

var ghoti = "????" // from character picker
print(ghoti) // ????
ghoti = String(UnicodeScalar(0x1F41F)!)
print(ghoti) // ????

Cocoa also supports loading unicode characters by name using the \N{UNICODE CHARACTER NAME} escape sequence. You can use patterns to construct unicode characters as in the following example:

// Make sure to escape the backslash with a second
// backslash to allow proper string construction
"\\N{FISH}"
   .applyingTransform(StringTransform.toUnicodeName, 
        reverse: true) // ????
let constructed = "I want to eat a \\N{FISH} sandwich"
   .applyingTransform(StringTransform.toUnicodeName,
        reverse: true)
print(constructed!) // "I want to eat a ???? sandwich"

This is a reverse transform, in that it converts from escaped names to the symbol it represents. The forward transform takes a string and inserts name escape sequences in place of unicode characters:

let transformed = "????????????"
    .applyingTransform(StringTransform.toUnicodeName, 
    reverse: false)
// \N{DOG FACE}\N{COW FACE}\N{PILE OF POO}

Unicode escapes are also usable in Cocoa regex matching. This example searches for the little blue fish in a string, printing out the results from that point:

let fishPattern = "\\N{FISH}"
let regex = try! NSRegularExpression(pattern: fishPattern, options: [])

let string = "I wish I had a ???? to eat"

// You have to use Cocoa-style ranges. Ugh.
let range = NSRange(location: 0, length: string.characters.count)

// There's a fair degree of turbulence between 
// the Cocoa API and Swift here, especially with
// the Boolean stop pointer
regex.enumerateMatches(in: string, options: [], range: range) {
    (result, flags, stopBoolPtr) in
    guard let result = result
        else { print("Missing text checking result"); return }
    let substring = string.substring(from: 
        string.index(string.startIndex, offsetBy: result.range.location))
    print(substring) // "???? to eat"
}

It’s hard going back from Swift’s string indexing model to Cocoa’s NSRange system. Native regex can’t arrive soon enough.

You can also break down unicode scalars to components:

var utf16View = UnicodeScalar("????")!.utf16
print(utf16View[0], utf16View[1]) // 55357 56351
print(String(utf16View[0], radix:16), 
    String(utf16View[1], radix: 16)) // d83d dc1f

This scalar approach goes boom  when you try to push into highly composed characters:

Instead:

let utf16View = "????‍????‍????‍????".utf16
for c in utf16View {
    print(c, "\t", String(c, radix: 16))
}
// 55357 	 d83d
// 56424 	 dc68
// 8205 	 200d
// 55357 	 d83d
// 56425 	 dc69
// 8205 	 200d
// 55357 	 d83d
// 56422 	 dc66
// 8205 	 200d
// 55357 	 d83d
// 56422 	 dc66

It’s interesting to see the four d83d components in there.

Got any fun little Unicode tricks? Drop a comment, a tweet, or an email and let me know.

Update: 

Tuple assignments

Do you have any good examples of when it would be useful to have a tuple but be doing complicated enough stuff with them?

Here are some examples I grepped out of a local folder, including some from third parties:

var (x, y) = (7.5, 7.5)
let (controlPoint1θ, controlPoint2θ) = (dθ / 3.0, 2.0 * dθ / 3.0)
var (_, sceneWidth) = boundingNode.boundingSphere
let (vMin, vMax) = label.boundingBox
let (duration, _) = cameraController?.performFlyover(toFace: mainActor.rotation) ?? (0, 0)
struct Point { var (x, y) : (Double, Double) }

Hope that helps.