Swift is designed to be a “safe” language, which means it provides commands to help you write code that minimizes the risk of crashes. Of course, Swift is only as safe as the programmer, but Swift at least provides tools to minimize crashes, unlike C which provides multiple ways for programmers to shoot themselves in the foot.
One way crashes occur is when a variable gets a value of nil and can’t handle it. So the program crashes. That’s why Swift offers something called the nil coalescing operator, which looks like two question marks (??).
The nil coalescing operator lets you assign a variable to an optional variable. If the optional variable is nil, then the nil coalescing operator assigns the variable a default value.
In this example, we create an optional variable called “str” and assign it the string “Value here”.
The second line tries to assign this optional variable to the “myString” variable. The nil coalescing operator tells Swift, “If the ‘str’ value is not nil, then assign it to myString. Otherwise assign the value ‘Safe value here’ to myString instead.”
The above code stores “Value here” in the myString variable. Let’s give str a nil value like this:
Because str is nil, myString now contains the value “Safe value here”.
As a general rule, if a variable can be optional, then make sure your code can work whether the optional variable is nil or not. This just makes your code safer and less likely to crash.
Posted in Algorithms
Xcode makes it easy to create user interfaces by simply dragging items from the Object Library and placing it on a view of your storyboard. However, user interface objects often are designed to appear a certain way. For example, the switch object that lets users toggle between on and off, is meant to appear horizontally.
When users click on the switch, the switch slides left and right, but what if you want the switch to appear vertically so clicking on the switch slides it up and down?
Logically, you would think Xcode would offer a feature that would let you rotate a user interface object as easily as you might rotate an object in a graphics program like Photoshop or Illustrator. Unfortunately, this doesn’t seem to be the case so you need to rotate user interface objects using Swift code.
First, drag and drop your user interface object on a storyboard of your project. Then control-drag to create an IBOutlet. Now use the transform and CGAffineTransform commands to rotate a user interface item.
Suppose you created a switch on a storyboard that you want to rotate. In your Swift file (such as the ViewController.swift file), make sure you have an IBOutlet so you manipulate it using Swift code such as:
Now define the angle you want to rotate the object, declaring it as CGFloat. Oddly, if you want to rotate an object, -90 will actually be too far so you need to experiment with other values instead. To rotate a switch vertically, the angle must be specified as -89.55 as follows:
Now use the transform and CGAffineTransform commands to rotate the switch like this:
So if you create an iOS project and place a switch on the user interface, your complete code in the ViewController.swift file can look like this:
By using Swift code, you can rotate user interface objects on your user interface. You can download an example program below.
Posted in Algorithms, iOS, User Interface
If an array contains numbers such as integers or decimal numbers, it’s fairly simple to write a function that adds all the elements of an array using a for-in loop. For example, assume you have an array of integers like this:
Now to add all these integers in the array together, start by assuming the total value is 0. Then keep adding each array item until you get a total. A for-in loop might look like this:
This for-in loop is straightforward, but Swift offers a method for manipulating arrays called reduce. The reduce method lets you define an initial value and a closure, which is essentially the guts of a function written in condensed form. As an alternative to adding array items using a for-in loop, you could just use a closure like this:
This defines an Int variable called “Total” that uses the reduce array method to calculate a value. In this case, the initial value is 0. Then it takes one value in the array (x) and adds it with the next value in the array (y). This gives us the exact same result as the for-in loop.
The for-in loop is obviously clearer and easier to understand. The reduce method with a closure is more elegant but harder to understand. Since closures can look so odd, it’s probably best to add comments that explain how they work and even write short code that duplicates what the closure does. This will help others better understand what the closure does and how it works.
To read more about the reduce method for arrays, click here.
Posted in Algorithms
When working with angles, most people are comfortable measuring angles using degrees, but many of Apple’s frameworks expect radians. To convert degrees to radians (or vice versa), you could write your own conversion functions, but there’s no reason to do so since Apple’s GLKit framework includes such conversion functions.
All you have to do is import the GLKit into your project to gain access to its conversion functions. Then define degrees or radians as a Float data type.
To convert degrees into radians, use the GLKMathDegreesToRadians function.
To convert radians into degrees, use the GLKMathRadiansToDegrees function like this:
The above code will convert 360 degrees into 6.283185 radians and then convert 6.283185 radians back to 360 degrees.
Posted in Algorithms
On many Apple products when you type in a password incorrectly, the text field appears to “shake” back and forth as if telling you, “Nope. You entered a password incorrectly.” To create this shaking effect on a text field, you need to create an extension.
Extensions let you define new methods for manipulating an object. Since a text field is an object, created from the UITextField class, it’s possible to extend this UiTextField class with a custom shaking function.
To see how this works, create a Single View App iOS project and add a text field and a button on the user interface. Create an IBOutlet for the text field like this:
Then create an IBAction method for the button like this:
This simple project works by displaying a text field and a button. If you type a password correctly in the text field, then the text field displays the text “ACCESS GRANTED”. However, if you type an incorrect password, then the text field runs a shake function. To create this shake function, you need to create an extension at the bottom of the ViewController.swift file past the last curly bracket like this:
This shake function defines an animation that lasts 0.05 seconds, repeats itself 5 times, and moves the text field 4.0 pixels to the left and 4.0 pixels to the right, which creates the “shaking” visual effect.
Your complete ViewController.swift file should look like this:
When you run this app in the Simulator, type the word “password” in the text field and you’ll see the words “ACCESS GRANTED” in the text field. If you type anything other than “password” in the text field, the text field will shake back and forth.
By using extensions, you’ve extended the text field to make the shake() method available to the text field. Any time you want to modify a user interface item, use an extension to modify that object’s behavior.
Posted in Algorithms, User Interface
With most older programming languages, printing data of different types can be a nuisance since you typically have to convert everything into a string. Swift avoids this hassle by simply letting you identify data to print or store into a string using the \() symbols such as:
The above code simply stores a decimal number (1.2547032) into a variable that stores Double data types. (The Double data type is assumed by Swift.) Then rather than convert that Double variable into a string, Swift just lets you store that data as a string using the \() symbols.
If you try the above code in a Swift playground, you’ll find that the print statement simply prints the string “1.2547032”.
When printing or converting decimal values into strings, you might not want to display all the decimal values. A simple way to define exactly how many values after the decimal value to display is to use a format specifier.
If you’re familiar with the C programming language, you may already know that you use a % followed by a decimal point, and then the number of decimal places you want to display, followed by the “f” letter that stands for floating point like this:
This code simply turns the number 1.2547032 into a string with two decimal places or 1.25. Then it prints the string “1.25”.
By using a format specifier to print or convert decimal values to a string, you can show as many decimal places as you wish such as two or three.
Posted in Algorithms
Apple recently added machine learning features in a framework called Core ML. The idea is that you can take machine learning models and plug them into any Xcode project to instantly add machine learning capabilities to your apps. While this is exciting since this makes adding artificial intelligence (AI) to any app quick and easy, it’s not without its drawbacks.
First, let’s talk about the drawback of machine learning in general. In the book “Weapons of Math Destruction,” author Cathy O’Neil explains the inherent limitations of machine learning. Someone must first create an algorithm and then that algorithm is only as good as the data that it trains on. Feed the algorithms he wrong or misleading data and it can’t help but reach incorrect conclusions.
For example, Microsoft once created an AI chat bot that could learn from comments people submitted. So people started submitting racist comments so the AI chat bot would repeat nonsense about the Holocaust never happening and blaming Jews, blacks, and Mexicans for the problems in the world. That example simply shows if you train a machine learning model with bad data, you get back bad results.
Second, machine learning only works when the machine learning model can learn and improve its decisions. Without feedback, the machine learning model has no idea whether it’s coming up with the right conclusions or not. Those twin problems are what Cathy O’Neil highlights in “Weapons of Math Destruction.”
One example she gives is how many school districts are using computer algorithms to determine the “best” teachers. To do this, the programmers who created the algorithm can’t take into account all possible factors so they choose the ones they think (rightly or wrongly) that matter most in evaluating a teacher.
This caused the algorithm to rate one teacher as a 6 (on a scale of 1 to 100) one year, and then rate that same teacher a 96 the following year. How can a teacher go from a dismal 6 rating to an excellent 96 rating in one year? It’s because the first year, the teacher taught advanced students so their test scores were high to begin with, and remained high by the end of the year so they showed no improvement. the algorithm incorrectly assumed that no improvement in test scores meant that the teacher wasn’t any good.
The following year, that same teacher taught ordinary students and their test scores went up, so the algorithm assumed that the teacher did a good job. By not taking all factors into account and even worse, not accepting any feedback for modifying the machine learning model, this algorithm for evaluating teachers generates false and misleading results. yet because a computer generates these results in a seemingly objective way, people wrongly assume the computer must be correct when it’s not.
Even worse, the results of these skewered answers affects the lives of people, often in negative ways. Trying to argue that a computer algorithm is wrong is often a pointless and fruitless effort, and that’s the problem with machine learning.
Now in the world of Xcode, Core ML seems to have several faults. First, it’s not easy to create a machine learning model. That’s why Apple offers several machine learning models on their website. Second, there are plenty of machine learning models available that aren’t stored in the Core ML format, so Apple offers a bunch of tools for converting these machine learning models into Core ML files.
Unfortunately, installing and using these tools is clumsy and error-prone, making the process difficult for all but hardened developers. Apple will likely fix this process, but right now, it’s a huge pain in the neck. Still if you can get it to work, you can theoretically convert most machine learning models into Core ML files so you can add them to any Xcode project. That means you can add AI capabilities to macOS, iOS, watchOS, or tvOS apps.
Perhaps the greatest limitation of machine learning models is that once you have them stored on Core ML format, can you modify these models to make them more intelligent so they actually learn over time with new data?
If you can modify a machine learning model over time, then how do you do it and how do you keep it from making mistakes such as what happened with Microsoft’s chat bot that learned to swear and offer racist comments?
If you can’t modify a machine learning model over time, then it’s inherently limited. If you try several of the machine learning models that Apple provides, you’ll find that they’re only average in recognizing images in pictures.
So machine learning has a great future in making apps smarter. The problem is that machine learning is still limited and difficult. That will only get better over time and machine learning models will get smarter over time as well.
Until then, machine learning is the future so you better know how to add machine learning models to your Xcode projects. Just don’t expect miracles just yet, and keep in mind that “Weapons of Math Destruction” highlights the danger of relying too much on algorithms that we don’t fully understand and can’t modify.
Machine learning has its place, and it’s firmly in assisting humans, not substituting actual thought for machine learning results.
Posted in Algorithms, Programming, Xcode
When you’re working with numbers, you may want to convert the number to a string. The simplest way to convert a number to a string is to use the String data type to convert a number to a string like this:
A fancier way to convert a number to a string is to use the NumberFormatter class. At the simplest level, the NumberFormatter class just duplicates the String data type conversion like this:
In the above code, the first line creates an object (myNumber) from the NumberFormatter class.
The second line converts a number (24) to a string and then stores that number into a constant named costString (“24”).
The NumberFormatter class can also convert a string into a number such as turning “9.4” into 9.4 like this:
In this example, the line converts the string “9.4” into a number (9.4) and stores it into the newStuff variable.
Of course, you could just use the Double data type to convert a string into a number like this:
The first line creates a string variable that contains “4.2” as its value. The second line then uses the Double data type to convert the string from “4.2” to 4.2 as a Double value.
Up until this point, the NumberFormatter class simply duplicates the String and Double keywords to convert a number to a string or a string to a number. What makes the NumberFormatter class unique is that it offers the ability to spell out a number:
The first line defines an object called myNumber based on the NumberFormatter class. Then the second line defines the numberStyle property as .spellOut, which means it converts a number into actual words.
The third line above creates a string from the number 742.409 but spells this out as the string “seven hundred forty-two point four zero nine”, which it stores into the variable x.
The NumberFormatter class is just one of those oddball classes that you may find useful once in a while, so experiment with the NumberFormatter in a Swift playground and see how it works for yourself.
Posted in Algorithms
Safety is crucial in most modern programming languages because programs that allow the wrong types of data will likely fail or crash the program completely. That’s why real-time avionics programs that control jet airliners rely on safe programming languages like Ada.
Swift emphasizes safety as well, and one feature that Swift offers is called the guard statement. The basic structure of the guard statement looks like this:
The guard statement looks to make sure a condition is true. If the condition is false, then exit out of a function without running any code.
By placing a guard statement at the beginning of a function, you can check to make sure all data is valid before running any code. A simple example of a guard statement might look like this, which you can paste and run in a Swift playground:
This code checks to see if a number (stored in the myNumber variable), passed into a function, is an odd or even number. If it’s even, then the guard statement lets any code following run. If the number is odd, then the guard statement runs and the return command stops any further code from running in that function.
When you pass the number 4 into the testGuard function, the guard statement lets it run the testGuard code, which prints “Even number”. When you pass the number 5 into the testGuard function, the guard statement catches it, prints “Odd number”, and then exits out of the function.
By placing a guard statement at the beginning of each function, you can make sure that function only receives valid data. By using the guard statement, you can make your code more reliably.
Posted in Algorithms
When you create a macOS project that uses storyboards, each window is called a view, which has a border. Two ways to modify the border of a view is to change its width and change its color.
To change the view’s border width, you need to use the borderWidth property like this:
One way to make it easy to change the width of a border is to use a slider. Then create an IBOutlet for that slider along with an IBAction method like this:
To change the view’s border color, you need to use the borderColor property like this:
The simplest way to change the border color is through a color well. Just create an IBOutlet and an IBAction method for that color well, in addition to overriding the changeColor function like this:
If you have a slider and a color well on your view, users can drag the slider back and forth to modify the border width and click on the color well to choose a different color for that border. You can download a sample program that shows how this works:
BorderSetting sample program.
Posted in Algorithms, User Interface