Swift Oneoffs

Prenez
2 min readJan 27, 2019

--

Just some comments on the simple stuff.

Reading Chris Eidof’s Advanced Swift, updated for Swift 4.

The trick with Swift programming isn’t the code, which is easy to understand — it’s the eyes and getting them to read the ‘funny syntax’ where you breezily pass around functions that returns things, which means you’ll often see stuff like

func myCurrentFunction (aFunction: (anElement -> something) -> somethingElse

…and you’re poor brain is going “two -> in a row! What could it all mean?!”

Your eyes and brain have to learn to glue that first -> to the function and realize that’s the total function, the function body and the value it returns, and that it’s meant to be run inside your current function — which is what returns that SECOND value. You should read it like this:

1 Oh, a function that returns something (anElement -> something)

2 Oh, aFunction is being passed in as a parameter into myCurrentFunction

(Element is the associated type, the type being the type of the function that is passed in)

3 Oh, aFunction isbeing called inside myCurrentFunction.

4 Oh, myCurrentFunction also returns somethingElse, probably based on the results, in some way, of aFunction.

5 Oh, there it is

(aFunction(anItem))

and sure enough that call returns something, and that something is tested

6 Oh, based on the test of something, now myCurrentFunction is going to return somethingElse.

So you break it up in your head:

myCurrentFunction -> somethingElse {

  • aFunction -> something
  • return somethingElse

}

Just pop your eyes between the beginning and the end of the function signature, scoop up the main function and what it returns, and then dive into the parameters and parse out what’s there, a passed in function.

To go back to discussing this function:

In plain English, you have a function called last.

  • where is the external name of the parameter, and predicate is the internal name of the parameter.
  • the parameter Element (a placeholder for the associated type) is a function that returns a Bool.
  • the function you will pass in is:

names.last {$0.hasSuffix(“x”)

  • the for loop goes through each item in the array and runs the hasSuffix function on the element
  • the first time the passed in function produces a Bool TRUE, then the element is returned and the outer function ends
  • otherwise, if the passed in function never produces a true, then the outer function returns nil

The effect is, it finds, in the reversed list, the first element of a person whose last name ends in ‘a’.

That’s it.

--

--

Prenez
Prenez

Written by Prenez

Writes iOS apps in Swift and stories in American English.

No responses yet