Category: 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

January 23rd, 2017 by admin

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:

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

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:

let colorPanel = NSColorWell()

Now inside your IBAction method, add code like this:

    @IBAction func changeBKColor(_ sender: NSButton) {
        colorPanel.activate(true)
        colorPanel.action = #selector(changeColor)
    }

You’ll need to create a changeColor function like this:

    override func changeColor(_ sender: Any?) {
        self.view.layer?.backgroundColor =  colorPanel.color.cgColor 
    }

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:

import Cocoa

class ViewController: NSViewController {

    let colorPanel = NSColorWell()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func changeBKColor(_ sender: NSButton) {
        colorPanel.activate(true)
        colorPanel.action = #selector(changeColor)
    }

    override func changeColor(_ sender: Any?) {
        self.view.layer?.backgroundColor =  colorPanel.color.cgColor 
    }

}

Posted in Algorithms, macOS

January 20th, 2017 by admin

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:

let aDecimal = 2.3094

var stringHere : String

stringHere = "This is a string = \(aDecimal)"

print (stringHere)

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:

let aDecimal = 2.3094

var stringHere : String

stringHere = "This is a string = " + String(aDecimal)

print (stringHere)

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:

let formatMe = NumberFormatter()

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:

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2

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:

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

To retrieve a string from a number, you must use a number of the NSNumber data type such as:

let aDecimal : NSNumber = 2.3094

Now you’ll be able to convert a number into a string using this command:

formatMe.string(from: aDecimal)!

So the whole code would look like this:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

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:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .currency
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

If you wanted to display a decimal like 2nd, you could use this code:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .ordinal
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

If you wanted to display a decimal like 230.94%, you could use this code:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .percent
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

Finally, if you want to display a decimal like “two point three zero nine four” you could use this code:

let aDecimal : NSNumber = 2.3094

var stringHere : String

let formatMe = NumberFormatter()
formatMe.maximumFractionDigits = 2
formatMe.roundingMode = .up

formatMe.numberStyle = .spellOut
stringHere = "This is a string = " + formatMe.string(from: aDecimal)!

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

December 21st, 2016 by admin

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:

@IBOutlet var myWindow: NSView!

Assuming you named your window IBOutlet myWindow, you’ll be able to access the frame.width and frame.height properties like this:

myWindow.frame.height
myWindow.frame.width

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.

print ("Window height = \(myWindow.frame.height)")
print ("Window width = \(myWindow.frame.width)")

Posted in Algorithms, User Interface

HTML Snippets Powered By : XYZScripts.com