A Lovely Computer

Capítulo 14. Swift

Part III. The Platform Owns It5 min · en inglés

14

Swift

I have written in Swift, and in Kotlin too. It was unfamiliar at first, I retrained quickly, I liked the syntactic sugar, the code got shorter and more expressive, and I did not pine for square brackets. Swift suits me. Which makes it all the more interesting to see what my loop of 2011 turns into in it, the one where the name of the method was taken from a database:

enum DeviceType { case neo, endpoint }

for dev in devices {
    switch dev.type {
    case .neo:      setNeo(dev)
    case .endpoint: setEndpoint(dev)
    }
}

The string from the database is gone. The kinds of device are listed in advance, the switch statement names each of them, and if I add a third kind and forget to write a branch for it, the program will not build, and the compiler will tell me that the switch must be exhaustive. In 2011 I would have learned of the same mistake on the bench, when the new device’s turn came. This is the same switch statement with which the task is solved in Java, and in Swift it does not bother me.

There is no message in Swift by default. When I call a method of an ordinary class written in Swift, the compiler either knows the exact address of the code or takes it from a table made at build time, and no lookup by name happens while the program runs. For a call to go the old way, through objc_msgSend, the method has to be marked with the word dynamic, and for an object to answer to a name written as a string, its class has to inherit from the old NSObject. The empty reference in Swift has also stopped silently accepting anything at all. A variable that may turn out empty has a special type, and the compiler will not let you touch it without stating explicitly what to do in case of emptiness.

Gratis, solo falta un paso

El resto del libro es gratis

Deja tu correo y te mando un enlace para confirmarlo. Después del clic, todos los capítulos se abren aquí, en este dispositivo, durante un año. Cuando salga un libro nuevo, escribiré a esa dirección; responde “basta” a cualquier correo y no vuelvo a escribir.

¿Tienes cuenta INITE? Entra y el libro se abre sin correo.

No se cobra nada por el libro. Si quieres apoyarlo, puedes donar desde cualquier capítulo.

Cómo se guarda la dirección