Parsing Int Variables in Swift - Optionals and Approaches

by Paul Solt in ,


Working with integer numbers in Swift is a little different, since the only string parsing method is toInt() and it returns an optional Int? value.

This means that you have to test the value before you use it, or it could be nil. Doing a force unwrap can result in a crash if you try to use the value.

Below are two approaches you can leverage using the if/else statements.

Approach 1

if let width = widthTextField.text.toInt() {
    if let height = heightTextField.text.toInt() {
        // Valid user input parsed
        println("Valid width: \(width), height: \(height)")
    }
}

Approach 2

var width = widthTextField.text.toInt()
var height = heightTextField.text.toInt()

if(width != nil && height != nil) {
    // Valid user input parsed
    println("Valid width: \(width!), height: \(height!)")
}

The benefit of the second approach is that you can test multiple optionals in a single line. You don't have to nest tons of if/else statements to make sure the values are valid.

I'd like there to be a better approach, but these are the two that I discovered from playing around with optionals. It would be nice if I could use the tuple syntax from a switch statement with the if let keyword.

Double Approach

Working with Double parsing is a different story. It doesn't look like their is a method on String, so you have to cast it to an NSString to convert. Going down that route you lose the Optional values. Invalid casts will return 0.

var width = (widthTextField.text as NSString).doubleValue

A Better Double Approach

The above code doesn't fail elegantly with optional values, and instead may give strange results. Use the NSNumberFormatter and get the double value from the NSNumber object it creates.

var numberFormatter = NSNumberFormatter()
var userInputString = "10.33a0" // 10.33
if let number = numberFormatter.numberFromString(userInputString)?.doubleValue {
    println("Converted user input: \(number)")
} else {
    println("Invalid number: \(userInputString)")
}


Connect

 


Swift 2 - How to get started with Xcode 6 on Mac

by Paul Solt in


Have you used Powerpoint, Pages, Keynote or Word?

Each of these apps helps you create media rich content, and that’s exactly what Xcode does. It’s an Integrated Development Environment (IDE) that organizes all your code, interface files, and image resources.

Xcode is the tool that you will use to create your iPhone and iPad apps. Along with Xcode you will use the iOS Simulator to test your first iPhone app on your Mac computer.

Learning how to use Xcode is your first goal. You don’t need to know how to do everything, but you should become familiar with the interface and the common buttons and panels.

Learn how to open Xcode

After downloading Xcode following the previous Swift 1 - Download Xcode and start your first iPhone app tutorial, you are ready to open up Xcode.

Welcome to Xcode 6

You will use Xcode to organize, create, and debug your iPhone apps. It provides a staging ground for you to design and test your code and resource files.

1. Open Xcode

You can open Xcode by clicking on it in your Applications folder, or by searching with Spotlight (Command + Spacebar) in the top right corner. 

Xcode 6 has a new look for the icon

Xcode 6 has a new look for the icon

2. Start a new Xcode project

You can create a new Xcode project from the Welcome to Xcode screen by clicking on the Create a new Xcode project button.

Start your first iPhone app from the Xcode welcome screen.

Start your first iPhone app from the Xcode welcome screen.

(Optional) Create a new Xcode project from the menu bar

In the menu bar click on File > New > Project…

The menu bar is the easiest place to create a new file or Xcode project

The menu bar is the easiest place to create a new file or Xcode project

3 Create a Single View iOS Application

The easiest place to start is with the existing project templates that Apple provides in Xcode. Your first app will be a single screen. To get started on the top left corner of the dialog select iOS > Applications > Single View Application

Create a Single View Application

Create a Single View Application

4. Edit your Xcode project options

When you create a new Xcode project you’ll have to pick a few settings. If this is your first iPhone app, these settings aren’t super important. You can change any of these settings later on, or on your next Xcode project.

During the learning process, you’re going to create a lot of Xcode projects. Think of each project as a separate learning experience, start a new one when ever you want to try something out.

  • Product Name: The name of your app
  • Organization Name: The name of your company (or just your name)
  • Organization Identifier: A unique text string, you can set it to anything. Apple has recommended reverse DNS, which means website name in reverse. I use PaulSolt.com and flip it to create com.paulsolt
  • Note: If your an iOS Developer, this text needs to match what you register with Apple to run the app on your iPhone. 
  • Bundle Identifier: A unique identifier for the app itself. This text is made from your Organizational Identifier and your Product Name. It’s a setting you can also change later.
  • Language: You can make apps with Swift or Objective-C.
  • Devices: Choose iPhone to start, or iPad if you want to target a bigger screen. Universal is the third option, which allows you target both iPhone and iPad devices. 
  • Note: With iOS 8 and Xcode 6 it will be easier to create apps for both devices without as much device specific coding.
  • Core Data: Turn this option if you want to use the local database that Apple created called Core Data. For your first set of iPhone apps, I recommend you leave this option off, unless you understand how to use a database.

Note: Core Data is important if your app is going to maintain a lot of local data about users or information. However, simple calculator style apps probably won’t need it.

Setup your Xcode project options

Setup your Xcode project options

5. Save your Xcode project

The last step is to save your project folder on your Mac. I recommend that you create a Projects folder on your Desktop.

Navigate to your Desktop > Click New Folder > Type Projects > Create

You’ll create a lot of small Xcode project folders. Keeping them in one place will help you organize your work.

Create Git repository: If this is your first Xcode project, leave option unchecked. This option is for version control (git) and it’s used to keep different versions of your code. It’s an important part of software development. To learn more, visit GitHub.com

You can see my code on Github at http://github.com/PaulSolt

Save your Xcode project in a folder on your Desktop

Save your Xcode project in a folder on your Desktop

Your first Xcode project

When you first open Xcode you will see a lot of panels and the project settings in the center. The area on the left will show code, image, and user interface files.

  • .swift files are your code files
  • .storyboard and .xib files are your user interface files
  • Images.xcassets contains images like your app icon

In the center of Xcode you’ll find the project settings. There is a button in the top left corner which shows and hides an inner panel, and there are tabs along the top.

The project settings contains information like the supported orientations (i.e. portrait or landscape or both). There are also build settings, which you can ignore for now.

The first screen of a new Xcode project

The first screen of a new Xcode project

Xcode’s Panels

The buttons on the top right corner of show and hide the various panels in Xcode. Here’s what Xcode looks like with all of the panels open. 

Along the top of each panel there are additional tab bar items, which will change the contents of a panel.

You will need to hide panels on a small monitor, like on the Macbook Air. If you want to keep everything open, get an external monitor or an iMac.

I love my 27” Thunderbolt Display

There are 4 main panels in Xcode

There are 4 main panels in Xcode

  • Navigator Panel: The navigator panel includes the following tabs: Project Navigator, Find Navigator (search), and Issue Navigator
  • Standard Editor: This is the code text editor, which can be a single code file or multiple code and user interface files (Assistant Editor).
  • Utilities Panel: Context sensitive options will appear in the Utilities Panel. If you have a code file open, you’ll see different options than a user interface file.
  • Debug Panel: When you run your app with the Play button, you’ll see the bottom panel appear if there is a crash, or if your app logs any text out from a print command. There are two buttons in the bottom right corner to toggle the Variables view or the Console view.
  • Toolbar: The top toolbar contains the most common used functions such as starting and stopping your app or choosing what device to run it on (iPhone 6 Plus vs iPad vs iOS Simulator). The buttons on the right side control the visible panels.

Press Play

You can run your first iPhone app right out of the box. Press the play button in the top left corner of the Xcode toolbar.

The Play and Stop buttons look like music playback buttons

The Play and Stop buttons look like music playback buttons

When you run the app it should work and you’ll see a message in the center of Xcode. It should say Build Succeeded. If you didn’t do something correct it might say Build Failed.

Success

Success

Something's wrong

Something's wrong

Navigate Xcode Efficiently with Keyboard Shortcuts

You will become much more proficient with Xcode if you learn some of the Keyboard shortcuts. Try to incorporate one or two of the top 14 keyboard shortcuts for Xcode into your workflow.

Watch the Xcode Introduction Video

Connect

Subscribe to learn more about Swift programming and iOS app development.

Swift iPhone App Courses

Signup for a beginner Swift app programming course. Learn from daily lessons and code exercises with instructor support.

Absolutely fantastic. It’s about time there was a high quality class available online to learn about iPhone app development. Definitely would recommend!
— Dot Fuz