Friday, January 2, 2015

A cup full of Swift for Java Programmers

I am imbibing the Apple Kool-Aid.  

I have upgraded from a shot-glass to a coffee cup.

I'm just going to jump in here today with an example of a function so that we can compare the method signature of a Java method with a function in Swift:

//for your playground
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
    var min = scores[0]
    var max = scores[0]
    var sum = 0
    for score in scores {
        if score > max {
            max = score
        } else if score < min {
            min = score
        sum += score
    return (min, max, sum)
let statistics = calculateStatistics([5, 3, 100, 3, 9])

The first line right away there's the keyword func.

This is necessary since a function can be defined as a standalone thing without the OOP-fetish containing object that Java requires.

Then we have a name, done in camelCapsStyle.

Then we have the input signature which (can have two names, one for internal & one for external use but) in this example only has one name "scores" which is an array of type Int.

Then there's the -> symbol which denotes the Output.

And in this example we see that Swift allows you to return multiple named values inside a Tuple.

Then there is the code block inside of the {} brackets which explains how that output comes to be.

The last 3 lines are specifically for your playground - the first calls the function with an array of sample data to construct the reply, the second references one of the returned output values by name and the last line returns the same value by index value of the returned tuple.

In java the method signature would look something like:

public Tuple calculateStatistics(int[] scores){}

And you would have to know to decode the 3 values in that returned Tuple without any hints. 

This method would need to exist inside some kind of container object, if only for namespace considerations.

More likely you would create 3 distinct methods, one for minimum, one for maximum and one for average and if you really needed the Tuple then a third method which would in turn call the first three.

All of that is of course still possible, but the point is that it is no longer necessary since Swift gives you this flexibility.

No comments:

Post a Comment