How to Create Outlets and Actions in Xcode Using Swift - Swift Tips 6

Xcode with the Assistant Editor (Venn Diagram button) let's you connect code and UI (user interface) files together.

In order for you to make your UI interactive, you need to create connections from the UI to your related code files. These connections give Xcode names that you can use in your code file to modify how something looks programmatically or to respond to user input (button tabs, sliders, switches, etc). There are two primary connections you will create in Xcode: outlets and actions.

Outlets

Outlets enable you to give a UI element a name that you can use in your code. You can create a connection from a label to your code file using an outlet.

Outlets will look like:

@IBOutlet weak var textLabel: UILabel!

You can modify properties associated with your UI element, like text and textColor for UILabel objects.

Actions

Actions let you trigger things that can happen in response to user input. When a user moves a slider, enters a date, or types their name you can run a chunk of code to respond to it.

Actions will look like:

@IBAction func buttonPressed(sender: AnyObject) {

    print("hi developer")

    textLabel.text = "you pressed me "
}

Creating Outlets and Actions

  1. Open the Assistant Editor
  2. Right-click and drag from your UI element (i.e. label) to the code file
  3. Xcode auto inserts code for you to create the name and connection

Variables and Properties

You can also create variables and properties in your Swift code files. For ViewController.swift files it is easier to initialize variables and properties when you declare them, or in your viewDidLoad() method.

Swift Tips Source Code

Grab the source code for this Swift Tip and many more at: http://SuperEasyApps.com/SwiftTips

3 Common Crashes for Beginner iPhone Developers in Xcode using Swift

3 common crashes for beginner iphone developers in xcode using swift

As you work with your first iPhone app you will inevitably run into different crashes. The three most common crashes are what every beginner encounters. If you know what to look for, you can avoid these in the future.

Two of the crashes are real crashes and one is because you clicked and mistakenly added a breakpoint, which is used for finding bugs.

Here are the three crashes and how to fix them:

  1. Breakpoint Crash

    • Problem: Thread 1: breakpoint 1.1
    • Why: You clicked in the gutter left of your code and added a blue flag.
    • Solution: Delete or disable the breakpoint (blue flag) from the code gutter.
  2. Storyboard IBOutlet Crash

    • Problem: Thread 1: signal SIGABRT
    • Console:

      Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<ViewController 0x7fbd74a090d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key spellingMistakee.'

    • Why: You deleted an Outlet/Action connection in code or renamed it (i.e. spelling mistake).

    • Solution: Right-click on the UI element and remove the old Outlet/Action connection mentioned as the key in the top of the Console output.
  3. Nil Optional Crash

    • Problem: Thread 1: EXC_BAD_INSTRUCTION
    • Console:

      fatal error: unexpectedly found nil while unwrapping an Optional value

    • Why: You removed a UIView IBOutlet connection and then used the IBOutlet variable in code. The variable has no value until you reconnect it to the UI element.

    • Solution: Right-click and drag from the UI element to the IBOutlet property that Xcode stopped at with the EXC_BAD_INSTRUCTION.

How to remove an array of objects from a Swift 2 Array - removeObjectsInArray

removeObjectsInArray Swift Protocol Extension.png

I was working on a game project in Swift and I wanted to remove objects from an Array, only to discover that my goto method from Objective-C’s NSMutableArray (removeObjectsInArray:) didn’t exist.

Removing multiple objects from an Array takes multiple steps – when you iterate over an Array you cannot remove objects. It’s a two step process, you need to discover which objects need to be removed and then you need to iterate through that list and remove each one, one at a time.

The code has changed between Swift 1.2 and Swift 2 – I’ll include both to show the differences.

Swift 1.2 Remove Multiple Objects from an Array

You can start by creating an array of objects – add to the end with append() or insert() at a specific index.

Next you will need to search for something in your Swift Array – for this example you’ll look for words with a specific letter. 

Lastly you’ll need to remove each word that contains the letter one at a time, outside of your first loop.

// Swift 1.2
var wordArray = ["Apple", "Carrot", "Peanut Butter"]
wordArray.append("Hummus")
wordArray.insert("Greek Salad", atIndex: 0)

// Find the objects to remove
var wordsToDelete: [String] = [String]()
for word in wordArray {
    if contains(word.lowercaseString, "p") {
        wordsToDelete.append(word)
    }
}

// Find the index and remove each object
for word in wordsToDelete {
    if let index = find(wordArray, word) {
        wordArray.removeAtIndex(index)
    }
} 

Swift 2 Remove Multiple Objects from an Array

Swift 2 changes the contains() function to a contains() method using Protocol Extensions and since we’re working with Swift 2 Strings – the character property needs to be used.

The global find() function is now replaced by the new indexOf() method on Array (technically CollectionType).

// Swift 2
var wordArray = ["Apple", "Carrot", "Peanut Butter"]
wordArray.append("Hummus")
wordArray.insert("Greek Salad", atIndex: 0)

// Find the objects to remove
var wordsToDelete: [String] = [String]()
for word in wordArray {
    if word.lowercaseString.characters.contains("p") {
        wordsToDelete.append(word)
    }
}

// Find the index and remove each object
for word in wordsToDelete {
    if let index = wordArray.indexOf(word) {
        wordArray.removeAtIndex(index)
    }
} 

 

Swift 2 Array Protocol Extension removeObjectsInArray

With the basics of removing objects from an Array you can take it a step further to get back to a single line of code to remove objects.

Using an extension in Swift 2 allows you to add functionality that’s missing from the Array type. An Array is a structure, so you’ll have to use the mutating keyword and the Element is the type of object that is in the Array (generics).

Equatable means that the type must support the == (equal to) method, which is required to find an object. String objects are already equatable, so you don't need to do any extra work. If you are storing a custom object you will need to implement your own isEqual method.

// Swift 2 Array Extension
extension Array where Element: Equatable {
    mutating func removeObject(object: Element) {
        if let index = self.indexOf(object) {
            self.removeAtIndex(index)
        }
    }
    
    mutating func removeObjectsInArray(array: [Element]) {
        for object in array {
            self.removeObject(object)
        }
    }
}

With the Array Extension you can simplify your last 4 lines of code into a single line of code to remove an array of objects.

// Swift 2
var wordArray = ["Apple", "Carrot", "Peanut Butter"]
wordArray.append("Hummus")
wordArray.insert("Greek Salad", atIndex: 0)

// Find the objects to remove
var wordsToDelete: [String] = [String]()
for word in wordArray {
    if word.lowercaseString.characters.contains("p") {
        wordsToDelete.append(word)
    }
}

// Remove an array of objects
wordArray.removeObjectsInArray(wordsToDelete)

Free Online Swift App Course

Subscribe and get access to the Free iPhone App Course – you can make your first iPhone app using Swift.