That's the one!
Three lessons for you.
First, the documentation for array has many, many array
functions and convenience variables. You'll find most of Apple's APIs are rich with options.
As some point you'll find yourself asking, "How should I code three separate text fields into a birthdate for my application??" This is where you need to train yourself to stop and say: "I can't be the first developer to have this problem!" Then instead of coding it yourself, take a look into the documentation. Somewhere you'll find a method to create a date from text objects.
Second, every time you ran a method on an array
, Swift returns another array
. Then you can chain another method to the new array. And do it again. And again.
Some of the chained methods required you to provide extra code, called closures. This sort of functional programming makes Swift very expressive.
Is your code Swifty?
I'll add one addtional comment regarding syntax and style. Swift borrows from best practices of several modern languages. And in many places it's blazed new trails into readability and easy syntax.
In this spirit consider the modulus operator for a moment.
Modulus
returns the remainder of simple division of two numbers. This is a maths concept and exists in math libraries for most all languages ever. Even spreadsheets and databases support some form of the modulus
operator.
But is the syntax straight forward and readable?
In spreadsheets you might use a function named mod(x,y)
. In Swift you use the percent symbol, $0%2
. Then you have to know that if dividing by 2 returns zero, the number is even! But you have to negate that because you're looking for ODD numbers.
In short there is a lot of potential for error. Error in negating, error in divisors, error in interpretation.
So ask yourself, is there a Swiftier way to do this? That is, is there a way to make this syntax easier to write, easier to read, and easier to interpret? In many articles you might find the writer using the phrase, "This isn't very Swifty."
So this is a long-winded bit of advice. But the Swiftier way to write this is to use an Integer
function isMultiple(of:)
if myNumber.isMultiple(of: 2) {
// this is an EVEN number, because it's a multiple of 2.
}
Keep Coding