Category: Algorithms

May 15th, 2017 by admin

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:

guard (condition) else {
        return
    }
// do something here

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:

import Cocoa

func testGuard (myNumber: Int) {
    guard (myNumber % 2) == 0 else {
        print ("Odd number")
        return
    }
    print ("Even number")
}

testGuard (myNumber: 4)
testGuard (myNumber: 5)

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

May 4th, 2017 by admin

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:

self.view.layer?.borderWidth = 5

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:

@IBOutlet weak var borderSlider: NSSlider!

@IBAction func sliderChanged(_ sender: NSSlider) {
        self.view.layer?.borderWidth = CGFloat(borderSlider.intValue)
}

To change the view’s border color, you need to use the borderColor property like this:

self.view.layer?.borderColor = NSColor.blue.cgColor

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:

@IBOutlet weak var colorWell: NSColorWell!

@IBAction func pickColor(_ sender: NSColorWell) {
        colorWell.activate(true)
        colorWell.action = #selector(changeColor)
}
    
override func changeColor(_ sender: Any?) {
        self.view.layer?.borderColor = colorWell.color.cgColor
}

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

April 29th, 2017 by admin

Most of the time if you want text to appear on your user interface, you just type it directly into your user interface, such as editing a text field or label. You can also create and edit text using the Attributes Inspector pane as well, but if you need to display large amounts of text, it’s often easier to create and edit that text in a separate file.

Once you create a separate text file (not stored in a word processor format like the Microsoft Word .docx file format), you can then drag and drop that text file into the Project navigator pane.

When you drag and drop a file in the Project navigator pane, a window will appear to display options for adding a file. Make sure the “Copy items if needed” check box is selected.

To retrieve a file, you must specify the filename and extension. If you stored text in a file called “Xcode.txt,” then the filename would be “Xcode” and the extension would be “txt”.

If the text file exists, then you can store the contents of that file in a variable name. If the file can’t load or the file you specify isn’t found, then you need to handle this possible error so your program doesn’t crash. You can do all this with the following code:

        if let filepath = Bundle.main.path(forResource: "Xcode", ofType: "txt") {
            do {
                let contents = try String(contentsOfFile: filepath)
            } catch {
                // Contents could not be loaded
            }
        } else {
            // Xcode.txt file not found!
        }

The above code would store the contents of the “Xcode.txt” file in the “contents” variable. Just remember that if your file were called “Data.asc” then the above code would replace “Xcode” with “Data” and “txt” with “asc”.

To see how this works in a simple macOS program, download and run the following sample program that displays a text view in a window and a push button. By clicking on the push button, you can load the contents of the Xcode.txt file:

TextImport

Posted in Algorithms

April 25th, 2017 by admin

An array typically contains items of the same data type such as strings or integers. To declare an array to hold a specific data type, you just need to state the data type inside square brackets like this:

var beasts = [String] ()

Then you can just add items to the array using the append command like this:

beasts.append("tiger")
beasts.append("bear")
beasts.append("duck")

You can also define an array just by stuffing it with data right away like this:

var pets = ["Fido", "Rover", "Puff", "Goldy", "Pete"]

Once you fill an array with data, you can sort it using the sorted() method like this:

var beasts = [String] ()

beasts.append("tiger")
beasts.append("bear")
beasts.append("duck")

beasts.sorted()

This would create a sorted array that contains [“bear”, “duck”, “tiger”]. In the above code, the array appears sorted but the original beasts array is actually still unsorted. If you want to save the sorted results, you must store them in a new variable like this:

var pets = ["Fido", "Rover", "Puff", "Goldy", "Pete"]

let newArray : [String]
newArray = pets.sorted()

let sameArray = pets.sorted()

In this code, newArray is defined as an array of String data types. Then the sorted() data gets stored in the newArray variable.

Of course, you could just declare a new variable and store the sorted results in that new variable in one line. In the above example, sameArray is defined and given a value of sorted array data all in one line.

Typically an array doesn’t contain just one data type like a String or Int, but a structure that contains multiple fields such as the following:

struct Contacts {
    var first: String
    var last: String
    var phone: String
}

var rolodexFile = [Contacts] ()

This code creates an array of structures called Contacts where each Contact contains a first, last, and phone field that can hold a String data type. To create a structure, you need to define a variable and data for each field in that structure like this:

var employee = Contacts(first: "Fred", last: "Zimmerman", phone: "555-1234")

var prospect = Contacts(first: "Susan", last: "Acker", phone: "555-7894")

var salesContact = Contacts(first: "Bill", last: "Miller", phone: "555-2456")

This creates three variables (employee, prospect, and salesContact) that each contain a first, last, and phone string data. To add these structures to an array, you can just use the append command like this:

rolodexFile.append(employee)
rolodexFile.append(prospect)
rolodexFile.append(salesContact)

This creates an array that holds three structures. The first structure in the array is the name “Fred Zimmerman,” the second structure is “Susan Acker” and the third structure is “Bill Miller.”

Now to sort this array, you must specify the field to sort on. If we wanted to sort by the “last” field, you would use the sorted command like this:

let sortedContacts = rolodexFile.sorted {
    $0.last < $1.last
}

The above code would create sortedContacts array where the first structure is the name “Susan Acker,” the second structure is “Bill Miller” and the third structure is “Fred Zimmerman.”

The entire code for defining a structure, creating variables to store data in structures, creating an array of structures, and then sorting that array of structures would look like this in a Swift playground:

struct Contacts {
    var first: String
    var last: String
    var phone: String
}

var rolodexFile = [Contacts] ()

var employee = Contacts(first: "Fred", last: "Zimmerman", phone: "555-1234")

var prospect = Contacts(first: "Susan", last: "Acker", phone: "555-7894")

var salesContact = Contacts(first: "Bill", last: "Miller", phone: "555-2456")


rolodexFile.append(employee)
rolodexFile.append(prospect)
rolodexFile.append(salesContact)

let sortedContacts = rolodexFile.sorted {
    $0.last < $1.last
}

With an array of structures, you can sort on individual fields.

Posted in Algorithms

April 20th, 2017 by admin

The TouchBar replaces the largely useless row of function keys on some of the MacBook Pro laptops. Since Apple recently updated their iWork office suite to take advantage of the TouchBar, it’s likely that the TouchBar will eventually find its way to other Macintosh models including on an external keyboard for the iMac, mac mini, and Mac Pro.

Since the TouchBar will likely be another user interface accessory, it’s important to know how to write macOS programs that offer a TouchBar. If you’re writing macOS programs and don’t have a TouchBar, you can simply use the TouchBar Simulator.

To use the TouchBar Simulator, open Xcode and choose Window > Show Touch Bar (or press Shift+Command+5). If you run any macOS program that supports the TouchBar, you’ll be able to see how those programs offer shortcuts on the simulated TouchBar.

To add TouchBar support to your macOS programs, click on your Main.storyboard file to display your user interface, then open the Object Library window. In the search field, type touchbar and the Object Library will display all the touch bar items you can add, including NSTouchBar, which is the touch bar itself.

Drag the NSTouchBar from the object Library over the Window Controller in your storyboard. The TouchBar will appear directly beneath this Window Controller.

Now you can drag other TouchBar items from the Object Library window on to the TouchBar such as NSTouchBar Slider or NSTouchBar Button. For this example, drag NSTouchBar Color Picker on to the TouchBar.

Now the TouchBar needs its own class file, so choose File > New > File. Click macOS and then click the Cocoa Class icon. Then click the Next button. A new window appears, asking for your class name and subclass.

The name can be anything you want, such as TouchClass. What’s far more important is that the Subclass is NSWindowController.

Click the Next button and then click the Create button. This adds the TouchClass.swift file to the Navigator pane, Now the next step is to link this TouchClass.swift file to the TouchBar.

Click on Main.storyboard and click on the blue icon that appears in the top, middle of the Window Controller where you added the TouchBar. Choose View > Utilities > Show Identity Inspector. Click in the Class popup menu and choose TouchClass (or whatever name you chose for your class file).

Once you’ve connected the TouchBar to a class file, choose View > Assistant Editor > Show Assistant Editor. You want the assistant editor to display the TouchClass.swift file, but you may need to manually choose this TouchClass.swift file to make it appear in the assistant editor.

When opening the TouchClass.swift file, you may see an error message. Just let Xcode correct this error and it will likely add a @available line such as the following:

@available(OSX 10.12.2, *)

Now with the TouchBar displaying a color picker, control-drag from the TouchBar color picker to the  top of the TouchClass.swift file.

When a popup menu appears, choose the following:

  • Connection: Outlet
  • Name: colorIcon
  • Type: NSColorPickerTouchBar

This creates an IBOutlet to the color picker on the TouchBar with code that looks like this:

@IBOutlet weak var colorIcon: NSColorPickerTouchBarItem!

Modify the windowDidLoad functions follows:

    override func windowDidLoad() {
        super.windowDidLoad()
        
        colorIcon.isEnabled = true
        colorIcon.target = self
        colorIcon.action = #selector(colorPicked)

    }

When a popup menu appears, choose the following:

  • Connection: Action
  • Name: colorPicked
  • Type: NSColorPickerTouchBar

This creates an IBAction method. Now edit this IBAction method with one line of code like this:

    @IBAction func colorPicked(_ sender: NSColorPickerTouchBarItem) {
        window?.backgroundColor = colorIcon.color as NSColor
    }

Choose Product > Run and you should see your program’s user interface, but probably not any sign of the simulated TouchBar. To display the TouchBar, go back into Xcode and choose Window > Show Touch Bar (or press Shift+Command+5).

Go back to your TouchBar program and you should now see the simulated TouchBar visible. Click on the color picker on the TouchBar to display a range of colors. Each time you click on a color, the background of the window should display that color.

TouchBar Example

Posted in Algorithms, User Interface

April 16th, 2017 by admin

If you’re creating a macOS program, you may want to display a dialog box on the screen to alert the user of something, such as an error message of some kind. The simplest way to create a dialog is to use the NSAlert class like this:

        let myAlert = NSAlert()
        myAlert.messageText = "Message text"
        myAlert.informativeText = "Informative text"
        myAlert.runModal()

If you create a push button on a window and store the above code in an IBAction method for This code creates a simple dialog that looks like this:

The messageText property defines the bold text and the informativeText property defines the text that appears underneath.

As an alternative to displaying a modal dialog, you can also display a sheet instead by using this code:

        let myAlert = NSAlert()
        myAlert.messageText = "Message text"
        myAlert.informativeText = "Informative text"
        myAlert.beginSheetModal(for: self.view.window!, completionHandler: nil)

This creates a sheet like this:

A simple dialog that displays a message is fine. When the user wants to dismiss the dialog, he or she can just click the OK button. However in many cases, you may want to add up to three buttons on a dialog with custom text. To do that, you need to use the addButton method like this:

        myAlert.addButton(withTitle: "Save")
        myAlert.addButton(withTitle: "Delete")
        myAlert.addButton(withTitle: "Cancel")

To determine which button the user clicked, you need to use a switch statement. If you created a modal dialog using the runModal() method, your switch statement might look like this:

        switch myAlert.runModal() {
            case NSAlertFirstButtonReturn: print ("Save")
            case NSAlertSecondButtonReturn: print ("Delete")
            case NSAlertThirdButtonReturn: print ("Cancel")
            default: print ("Nothing")
        }

So if you placed a push button on a window, and created an IBAction method to display a dialog by clicking this push button, your entire code might look like this:

    @IBAction func showAlert(_ sender: NSButton) {
        let myAlert = NSAlert()
        myAlert.messageText = "Message text"
        myAlert.informativeText = "Informative text"
        
        myAlert.addButton(withTitle: "Save")
        myAlert.addButton(withTitle: "Delete")
        myAlert.addButton(withTitle: "Cancel")
        
        switch myAlert.runModal() {
            case NSAlertFirstButtonReturn: print ("Save")
            case NSAlertSecondButtonReturn: print ("Delete")
            case NSAlertThirdButtonReturn: print ("Cancel")
            default: print ("Nothing")
        }
    }

To determine which button the user clicked if you created a sheet, your switch statement would look slightly differently:

        myAlert.beginSheetModal(for: self.view.window!, completionHandler: { (returnCode) -> Void in
            switch returnCode {
                case NSAlertFirstButtonReturn: print ("Save")
                case NSAlertSecondButtonReturn: print ("Delete")
                case NSAlertThirdButtonReturn: print ("Cancel")
                default: print ("Nothing")
            }
        })

If you created a push button on a window with an IBAction method to open a sheet, your entire IBAction method code might look like this:

@IBAction func showAlert(_ sender: NSButton) {
        let myAlert = NSAlert()
        myAlert.messageText = "Message text"
        myAlert.informativeText = "Informative text"
        
        myAlert.addButton(withTitle: "Save")
        myAlert.addButton(withTitle: "Delete")
        myAlert.addButton(withTitle: "Cancel")

        myAlert.beginSheetModal(for: self.view.window!, completionHandler: { (returnCode) -> Void in
            switch returnCode {
                case NSAlertFirstButtonReturn: print ("Save")
                case NSAlertSecondButtonReturn: print ("Delete")
                case NSAlertThirdButtonReturn: print ("Cancel")
                default: print ("Nothing")
            }
        })

    }

By using the NSAlert class, you an easily create and display dialogs as modal dialog boxes or as a sheet. You an also customize the number of buttons (up to three) and retrieve which button the user clicked on.

Posted in Algorithms, macOS, User Interface

March 13th, 2017 by admin

If you need to run one type of animation after another in macOS, Swift provides a simple way to do this where the code looks like this:

        NSAnimationContext.runAnimationGroup({ (context) -> Void in
               // First animation code here
        }, completionHandler: { () -> Void in
              // Second animation code here          
        })

By itself, this runAnimationGroup code does nothing. What you need to do is put your animation code within the first set of curly brackets and when that first animation completes, then you can run a second set of animation if you wish.

Suppose you want to rotate an item such as a label and when it’s done rotating, flip it back to its original position. First, create a label and an IBOutlet such as:

@IBOutlet weak var lblMessage: NSTextField!

Once you have an IBOutlet to represent a label on the user interface, you can rotate it using this code:

    @IBAction func animateMe(_ sender: NSButton) {
        NSAnimationContext.runAnimationGroup({ (context) -> Void in
            context.duration = 5
            lblMessage.animator().frameRotation = 45
        }, completionHandler: { () -> Void in
            self.lblMessage.animator().frameRotation = 0
        })
    }

Thea love code takes five seconds to rotate a label (lblMessage) 45 degrees. When it’s completed, it changes the label’s rotation back to 0 again.

While this simple example shows how to rotate an item, the more important lesson is to see how the runAnimationGroup lets you combine two different types of animations where the second animation runs after the first animation completes. Any time you need to run two different types of animation back to back, use the runAnimationGroup structure.

Posted in Algorithms, macOS

March 6th, 2017 by admin

If you want to make an item on the user interface appear to fade away and reappear again, you can use something called the animator() method. Essentially all you have to do is create an IBOutlet for a user interface item (such as a button or label) and then apply the animator() method along with defining the alphaValue property to 0 (completely invisible) or 1 (completely visible).

Of course, if you assign a user interface item’s alphaValue property to 0, it will suddenly disappear, so that’s why you need to create a delay effect using the following code:

NSAnimationContext.current().duration = 3

This simply tells code to delay the animator() action by three seconds (or whatever number you assign to the duration property.

Create a simply macOS project using storyboards and place a label and a push button anywhere on the view. Create IBOutlet for the label like this:

@IBOutlet weak var lblMessage: NSTextField!

Now create an IBAction method for the push button (call it AnimateMe) and fill it with Swift code such as:

    @IBAction func animateMe(_ sender: NSButton) {     
        if lblMessage.animator().alphaValue == 1 {
            NSAnimationContext.current().duration = 3
            lblMessage.animator().alphaValue = 0
        } else {
            NSAnimationContext.current().duration = 3
            lblMessage.animator().alphaValue = 1
        }
    }

This code simply checks what the alphaValue of the label might be. If its value is 1 (completely visible), then it slowly fades the label away in three seconds and sets its alphaValue property to 0. This creates a gradual fade out visual effect.

If the label’s alphaValue property is already 0, then the above Swift code takes three seconds to slowly set the alphaValue to 1, which creates a fade in visual effect.

Obviously there’s more to animation using the animator() method but this can get you started in seeing how simple it can be to create animation in a macOS program.

Posted in Algorithms, macOS, User Interface

February 18th, 2017 by admin

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

February 3rd, 2017 by admin

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:

func x239(jke: String) {
    
}

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:

func printGreeting(name: String) {
    
}

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:

func printGreeting(name: String) {
    print ("Hello there, \(name)")
}

printGreeting (name: "Sam")

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:

func printGreeting(for name: String) {
    print ("Hello there, \(name)")
}

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:

printGreeting (for: "Sam")

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

HTML Snippets Powered By : XYZScripts.com