One of the reasons why artificial intelligence (AI) failed during the early days was because it required humans to program intelligence into a program. That meant exhaustively writing instructions for every possible outcome.
One of the earliest and more limited successes of AI were expert systems that consisted of a series of if-then rules to mimic the thinking process of a human expert. The reason why expert systems worked was because they could tackle a narrow niche with limited and known variables. The reason why expert systems ultimately failed is because they couldn’t advance beyond narrow niches and required humans to exhaustively write if-then rules for every possibility.
Even worse, when conditions changed, human programmers had to go back into the expert system to reprogram it and update it. This constantly meant consulting with a human expert and a human programmer, which made the expert system cumbersome to modify to the point where it wasn’t worth it at all.
That’s all changed with machine learning. The whole idea behind machine learning is to let a program teach and update itself. Not only is this far faster, but it’s far more accurate allowing the program to adapt to changing conditions. If you’re interested in machine learning with Swift, download the open source, Swift AI library.
This Swift AI library lets you create neural networks for both macOS and iOS. By incorporating machine learning in your apps, you can create more adaptive video games or smarter programs that can recognize handwriting or user behavior.
Trying to create machine learning tools on your own in Swift is possible, but clumsy. It’s so much easier to use a tested machine learning framework instead, so that’s why you might want to experiment with Swift AI.
As Swift gains popularity, it’s likely that others will create machine learning frameworks for Swift but until that day comes when we can choose from a variety of machine learning tools, Swift AI offers the best way to experiment with machine learning using Swift.
At the very least, dig through the sample programs in the Swift AI library and give yourself a rudimentary understanding of how machine learning works and how to implement it in Swift.
To download the Swift AI library for adding machine learning to iOS and macOS programs, click here.
Posted in Algorithms, iOS, macOS
In any programming language, you can choose arbitrary names for your functions and parameters. For example, you could create a completely valid but confusing function like this:
Notice that the function name (x239) and parameter name (jke) provides no clue what they do. Although this code is perfectly valid, it’s confusing so it’s always best to choose descriptive function names and parameter names such as:
This function name (printGreeting) and parameter name (name) is much clearer as to the functions purpose, which is to take a name and print a greeting. Of course, this function could actually calculate a differential equation so it’s generally best to choose descriptive function and parameter names that actually describe the purpose of the function.
To call this function, you could use code like this:
The function call uses the printGreeting name and identifies the name (“Sam”). This is perfectly fine but in Swift, you have the option to use external parameter names. This means you can have two parameter names, an external and an internal parameter name.
The internal parameter name is what the function actually uses while the external parameter name is what you use to call the function. So to make the function call read more like an actual sentence, you could use an external parameter name like this:
Notice that the function uses “name” as a variable for the actual code, but when you’re calling the function, you use the external parameter name like this:
Now the function call reads like a complete sentence such as “Print greeting for Sam.”
You may not want to do this for your own function declarations and calls, but you’ll find that many Swift API calls use external parameter names specifically to make function calls seem more like a sentence, typically using external parameter names of “in,”, “for”, and “with”.
External parameter names simply help make code more readable although at the expense of also making function declarations more cumbersome to write. You can choose to use external parameter names or not, but whether you use them or ignore them, you’ll at least better understand why so many of Apple’s API functions look the way they do using external parameter names.
Posted in Algorithms, iOS, macOS
When working with storyboards in a macOS project, you may want to change the background color of a scene (view). The simplest way to do that is to use this command:
This simply assigns the color blue (or whatever value you want to insert there such as red or yellow) to the background of the view layer. Of course, writing specific color values into code isn’t very efficient because if you want to change the color, you have to rewrite the code for a new color.
A far better solution is to change the color using code and the simplest way to do that is to assign the backgroundColor of a view to a variable that represents a different color. One way to do this is to use the Color Panel (see this blog post covering the Color Panel).
So if you create a simple macOS project that uses storyboards, place a push button on the view controller and create an IBAction method with a name such as changeBKColor. Declare a color panel underneath the class ViewController line like this:
Now inside your IBAction method, add code like this:
You’ll need to create a changeColor function like this:
If you run this program, a window will appear with a push button. Clicking the push button will run the IBAction method changeBKColor, which displays a color panel. Choosing a color from this color panel then changes the background of the view. The complete code in the ViewController.swift file should look like this:
Posted in Algorithms, macOS
Chances are good you’ll need to manipulate numbers. However, when you want to display those numbers as a text string to display in a label or text field, you’ll need to convert that number into a string.
The simplest way to convert a number into a string is to use the \( ) method inside quotation marks where you put the number inside the parentheses such as:
In the above example, the “stringHere” variable holds the text string “This is a string = 2.3094”. While this is fine, another method is to actively convert the number into a string by using String( ) where the number goes inside the parentheses such as:
This code works exactly like the previous code so the “stringHere” variable holds the text string “This is a string = 2.3094”. Either method is fine, but there’s a third way to convert numbers into strings and that’s to use the NumberFormatter class.
Some advantages of the NumberFormatter class include:
- Letting you define how many decimal places to display
- Letting you define whether to round up or down
- Letting you work with different number formats such as currency
To use the NumberFormatter class, you need to create an object such as:
Now you can specify the maximum number of decimal places you want to include. If you wanted to display two decimal places, you could use the following:
Once you’ve defined the maximum number of decimal places to display, you can also choose a rounding mode such as one of the following:
- down – always rounds down
- up – always rounds up
When rounding down to two decimal places, a number like 2.3094 would turn into 2.30.
When rounding up to two decimal places, a number like 2.3094 would turn into 2.31.
To define how to round numbers, you could use this code:
To retrieve a string from a number, you must use a number of the NSNumber data type such as:
Now you’ll be able to convert a number into a string using this command:
So the whole code would look like this:
Copy and paste this code into a Swift playground to see how the NumberFormatter class works to convert a number into a string. While using the NumberFormatter class might seem clumsier, it does give you more control over the decimal places to display and how to round a number.
What makes the NumberFormatter class even more useful is that it can convert numbers into one of the following:
- currency – displays the local currency symbol with the number
- ordinal – displays numbers like 2nd or 8th
- percent – displays numbers with a % sign at the end
- spellOut – types the text of the number such as “two point three zero nine four”
If you wanted to display a decimal as $2.31, you could use this code:
If you wanted to display a decimal like 2nd, you could use this code:
If you wanted to display a decimal like 230.94%, you could use this code:
Finally, if you want to display a decimal like “two point three zero nine four” you could use this code:
For simple conversion of numbers to strings, it’s much simpler to use either the \( ) or String( ) methods, but if you need unique formatting, then use the NumberFormatter class instead.
Posted in Algorithms
If you’re creating a macOS program using storyboards, you may need to know the size of a window. To get this information, you just need to follow two steps:
- Create an IBOutlet that represents your window. This IBOutlet should be of the type NSView
- Use the frame.width and frame.height properties to get the width and height of the window defined by your IBOutlet
To create an IBOutlet for a window, just opens he Assistant Editor, move the mouse pointer over the window, and Control-drag to the Swift class file linked to your window such as ViewController.swift. Then release the Control key and the left mouse button to create an IBOutlet.
You can use any name for your IBOutlet, but whatever name you choose will now represent your window such as:
Assuming you named your window IBOutlet myWindow, you’ll be able to access the frame.width and frame.height properties like this:
If you put the following two lines of code in the viewDidLoad function that runs as soon as a window appears, you’ll see the defined width and height of the window.
Posted in Algorithms, User Interface
If you’re creating a macOS program and need to identify the screen resolution of a Macintosh, you can get the height and width of the screen resolution by using the following code:
First you need to create a variable to represent the main screen (NSScreen.main()). Then you need to create a second variable (let resolution = myScreen?.frame) to identify the frame of the screen.
Now you can retrieve the width and height of the screen frame using the size.height and size.width properties. The above code uses the print command to retrieve the screen height and width but you could easily just store these values in a variable for your own program to use.
Posted in Algorithms, macOS
Swift contains four built-in founding functions:
- round – Rounds up from 0.5 and higher and rounds down from 0.49 and lower
- floor – Rounds to the lowest integer
- ceil – Rounds to the highest integer
- trunc – Drops the decimal value
To see how these different rounding function is work, just copy this Swift code into a Swift playground so you can see them in action:
However, if you want to round decimal numbers to a fixed number of decimal places, you may find the following function handy:
To use this function, you just need to define the number you want to round and the number of decimal places to display such as:
This Swift code would display three decimal places such as 18.178. Any time you need to round numbers to specific decimal places, add the roundToPlaces function to your own code.
To learn more about different rounding functions, click here.
Posted in Algorithms
The Cocoa framework contains standard panels your programs can use to Open, Save, or Print a file. Of course, you have to write code to make those panels work, but the Cocoa framework provides the code to display standard panels for your program to use.
One panel you can use is the Color Panel, which displays different colors for the user to choose from. To create a panel, you must first define a constant to represent that panel. For a color panel, the code needs to use the NSColorWell class like this:
Next, you need to actually display that color panel using the activate command:
Once you’ve activated the color panel to display it, you need to retrieve the color value the user chooses. To do that, you need to use the action and #selector commands to run the changeColor function like this:
You must write your own code in the changeColor function to make it actually do something. Assuming you have a label on your user interface called myLabel, you could change the label’s textColor property by retrieving the color panel’s color property like this:
So if you put a push button and a label on a window, clicking the push button would display the color panel. When the user chooses a color, the label’s text color would change. The complete code would look like this:
The main key to using the color panel is to call the changeColor function and add your own code to the changeColor function to make it do something.
As you can see, by using standard panels in your macOS programs, you can easily create a macOS program that looks and behaves like a regular macOS program without needing to write hardly any code.
Posted in Algorithms, macOS, Xcode
The switch statement in most programming languages replaces the more cumbersome if-then-else statement. Unlike the if-then-else statement, the switch statement in Swift may appear to only check if a variable is equal to a specific value such as:
The above switch statement is equivalent to the following if-then-else statement:
With if statements, you can check if a value is equal, greater than, or less than a certain range of values by using Boolean operators like OR (||) and AND (&&) value such as the following:
To duplicate this in a Swift switch statement, you can check if a variable falls within a range of values using the (…) or (..<) operators. The (…) operator lets you specify a range of values such as 2…10, which means a variable can match the lower bound (2), the upper bound (10), or any value in between (3, 4, 5, 6, 7, 8, 9).
The (..<) operator lets you specify a range of values where the last value specifies the upper bound that the variable cannot match. This means with a range of 2..<10, a variable can match the lower bound (2), or any value up to but not including the upper bound (3, 4, 5, 6, 7, 8, 9).
So the above if-then-else statement can be replaced with a switch statement in Swift like this:
Whatever you can do with the if-then-else statement, you can also do with the switch statement. Suppose you have an if-then-else statement that uses one of the following operators (<, <=, >, >=) without specifying a range such as:
You can still duplicate this with a switch statement by using the where keyword like this:
For checking equality (==), the switch statement is simpler and cleaner to read. For checking a range of values (…) or (..<), the switch statement is still simpler.
However, for checking for non-equal values using <, <=, >, or >=, then the switch statement is a little less clear but still simpler than a length if-then-else statement.
In general, the switch statement can do everything the if-then-else statement can do. If an if-then-else statement if short, it might be simpler than the switch statement, but if an if-then-else statement is large, then a switch statement will almost always be simpler and easier to read and write.
Posted in Algorithms
In most programming languages, a function can either perform a task or return a value. When a function returns a value, you can store that value in a variable such as:
In this example, the doubleNumber function accepts an integer, doubles it, and returns this doubled value. To hold this returned value, you can use a variable.
What most programming languages cannot do (but Swift can do) is create a function that can return two or more values. When a function returns multiple values, you can store those returned values in a tuple.
A tuple is nothing more than a variable that can hold multiple values. In Swift, you can define a tuple by simply defining the tuple name and the type of data it can hold such as a String or Int like the following:
This tuple can hold three Double values. Now if you have a function that returns three Double values, you can store them in this tuple.
To create a function that returns more than one value, you simply enclose one or more data types in parentheses. So if you want a function to return three Double values, you would define a function to return three Double values like this:
When a function returns two or more values, you can store those returned values in a tuple like this:
To access individual values trapped in a tuple, you can refer to them by index number where the first value in a tuple is at index 0, the second is at index 1 and so on like this:
The ability to return two or more values from a function makes Swift more flexible than other programming languages. Just use tuples to store the returned values.
Posted in Algorithms