Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all 4373 articles
Browse latest View live

Video Tutorial: Saving Data in iOS Part 1: NSString and NSData


WWDC Keynote – Podcasters React! Tech Talk Video

$
0
0

In a special session today right after the Apple keynote, raywenderlich.com podcasters Mic Pringle, Tammy Coron, Jake Gundersen, and Felipe Laso Marsetti reacted with their thoughts and observations, with some Q&A from viewers. There was plenty to discuss – improvements, new developer tools, and counting up the apps/companies that have been sherlocked!

Here’s the video for anyone who didn’t get a chance to watch!

Want to Join Us Next Month?

Thanks again Mic, Tammy, Jake, and Felipe for giving a great discussion and Q&A! And thank you to everyone who attended and asked questions – we hope you enjoyed it!

Next month, our July Tech talk will be on Facebook Pop Animation Library, with RW Team member Ryan Nystrom.

We will be broadcasting this talk live on Tuesday, July 1 at 2:00 PM EST, so if you want to join us sign up here! As you watch the talk, you can submit any Q&A you may have live.

WWDC Keynote – Podcasters React! Tech Talk Video is a post from: Ray Wenderlich

The post WWDC Keynote – Podcasters React! Tech Talk Video appeared first on Ray Wenderlich.

Swift Cheat Sheet and Quick Reference

$
0
0
Swift Cheat Sheet and Quick Reference Now Available!

Swift Cheat Sheet and Quick Reference Now Available!

Update 6/3: Updated thanks to some helpful comments/suggestions from Chris Wagner, @Craimasjien, @Alarcon, @doTheTricks, and @rbnVnznz. Thanks all!

I am up late tonight reading Apple’s Swift book and playing around with it a bit – there’s too much exciting stuff to sleep! :]

There’s a lot of new syntax in Swift, so I thought it might be useful if if I put together a cheat sheet / quick reference on the language.

Without further ado, here is the download link:

It summarizes the most important Swift syntax on one page to get you up to speed quickly, including:

  • Class Implementation
  • Methods
  • Creating/Using an Object
  • Declaring Variables
  • Control Flow
  • String Quick Examples
  • Array Quick Examples
  • Dictionary Quick Examples

I’ve made sure to use only materials available to the public in the creation of this.

This is just a quick first draft – let me know if you have any comments/suggestions on how to improve this. I’ll be updating this periodically as I learn more about Swift and hear your comments.

I hope this is helpful! Stay tuned for lots more Swift goodness on this site – especially after the NDA lifts :]

Swift Cheat Sheet and Quick Reference is a post from: Ray Wenderlich

The post Swift Cheat Sheet and Quick Reference appeared first on Ray Wenderlich.

Programming for Teens: Beginning Python Tutorial

$
0
0

Learn to code with Python!

Have you ever wondered how a computer works? While we can’t teach you everything in one blog post, you can get a pretty good start by learning how to write your own programs!

In this Python tutorial, you’ll learn the basics of programming a computer using one of the best languages for beginners.

What is Programming?

To put it as simply as possible, programming is the act of writing code that instructs a computer to perform a task.

A task can be as simple as adding two numbers together, or as complex as sending a spaceship into orbit!

The smallest element of a program is known as statement — this represents a single instruction to the computer.

All the things!

After you’ve written your program, a compiler converts the code you’ve written into machine code — the lowest-level language of a computer. Machine code instructs the central processing unit, or CPU, what steps to take such as loading a value, or performing some arithmetic.

If you’ve ever heard somebody say “I compiled my program”, it means they converted their code into machine code.

Why wouldn’t you just write machine code directly? The obvious reason is that program code is human readable. Compare the Python version of a program with its corresponding set of machine code below:

The Python Program

print "Hello, World!"
...
"Hello, World!"

The Machine Code Equivalent

c7 3c 2a 3c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c
28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c
2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b
2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c
3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28
5c 2a 2b 2a 5c 3c 28 5c 2a 2b 2a 5c 3c 28 5c 2a
2b 2a 00 00 01 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 64 48 65 6c 6c 6f 2c 20 57
6f 72 6c 64 21 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
...
"Hello, World!"

It’s quite evident why you don’t want to program directly in machine code. However, there are a few people who do — there’s no accounting for taste! :]

There’s one minor detail we left out above. Python is an interpreted language; you don’t compile it directly into machine code as we alluded to above.

Instead, Python uses something called an Interpreter. An interpreter is yet another program that compiles code into something called Bytecode, which is then converted into machine code as the program runs. You’ll read more about interpreters later.

When you finally run the program, the machine code you recently compiled is loaded into memory and read by the CPU to execute the program.

However, you don’t need to really understand the inner workings of compilers to get started programming in Python, but you should first make sure that you have Python installed.

Getting Started

If you’re on a Mac, you’re in luck — Python comes preinstalled on a Mac.

To use the Python interpreter on a Mac, open Terminal.app; you can find it either in your Applications/Utilities folder, or by typing Terminal directly into Spotlight, like so:

terminalspotlight2

Once Terminal is open, type the following command and press Enter:

$ python

You should see something that looks like the following:

Screen Shot 2014-03-10 at 10.47.36 PM

Note: If you don’t get the output shown above, post the output from Terminal on the forum and we’ll do our best to help you out!

Windows

The process is a little more involved on Windows — but then again, most things are on Windows! :]

First, visit the official Python downloads page in your browser.

Scroll past the Python 3.x.x versions, all the way down to Python 2.7.x. Download the Windows installer, run it, and follow the instructions it presents, accepting the defaults along the way.

Once the installer has finished, you’ll need to launch the interpreter.

On Windows Vista or Windows 7, launch the interpreter like so:

  1. Click the Start button in the lower left hand corner
  2. Click on All Programs
  3. Open the folder named Python
  4. Double click the IDLE interpreter

If you’re on Windows 8, launch the interpreter this way:

  1. Click the Start button in the lower left hand corner
  2. Type IDLE into the search bar
  3. Click on IDLE (Python GUI)

Regardless of how you launched the interpreter, you’ll want to make sure that it works. Type the following command in Terminal, or Command Prompt in Windows, and press Enter:

print “Hello World!

Although it doesn’t seem like much, you’ve just written your very first Python program! Printing Hello, World is often considered the de facto starting point when learning most languages.

The print command instructs the computer to print what follows on the screen — not print it out to your printer! Note the quotation marks around “Hello World”; anything contained inside the quotation marks is considered to be regular text and won’t be interpreted as an instruction.

Variables

Variables are a way of storing data in the memory on a computer; you’ll use them a LOT as you program. In some languages, variables have a specific type which indicates what kind of variable class they belong to.

In Python, you don’t have to declare your variable types. Don’t worry too much about that detail now; you’ll learn more about this a little later in the tutorial.

Type the following command into the interpreter and press Enter:

hello = "Hello World!"

This declares and sets the hello variable to the value Hello World. Now, instead of typing “Hello World” everywhere you need that string in your program, you can just use the hello variable.

Type the following command into the interpreter and press Enter:

print hello

This prints out the same thing as your Hello World example, but instead it’s printing out the value of the hello variable.

Variables can also be used to store numbers. Type the following commands into your interpreter:

x = 5
print x
y = 10
z = x + y
print z

Note: From now on, there may be multi-line statements of code for you to type in. Simply hit Enter after each line.

Try to guess what the code above does before reading the spoiler below:

Solution Inside SelectShow>

Variables are core to most of the programming you’ll do in your life. You’ll become intimately familiar with them as you work your way through this tutorial!

Variable Types

You encountered variable types a little earlier in this tutorial, but we didn’t cover them in any detail. Each variable type stores a different kind of value.

Note: For a complete list of built-in types in Python, check the official Python documentation.

So far, you’ve only dealt with two basic types in Python: integers and strings. You’ll also encounter boolean types which you can use to store True and False values.

Here’s a bit of detail on each of these variable types:

Integers

An integer is a whole number. Integers range from -2147483648 to 2147483647 on 32-bit machines, and from -9223372036854775808 to 9223372036854775807 on 64-bit machines.

You create an integer variable by simply typing the number without any quotation marks, as shown below:

foo = 5

Strings

A string is a sequence of characters; you can use a string to represent anything from text on a screen to entire web requests.

You create a string variable by surrounding the sequence of characters with quotation marks as shown below:

bar = "foo-bar"

Booleans

Booleans represent either True or False values.

You create a boolean variable by typing a capitalized True or False without quotation marks as shown below:

isFoo = True

There aren’t any quotation marks around the variable; if you did surround True with quotation marks, you’d be declaring it as a string variable instead!

Adding Strings and Integers

Python makes it really easy to hook strings together, also known as concatenation. You can convert values from integer types to string types using the str() command. Likewise, you can convert a value from a string to an integer by using int().

Enter the following commands into your interpreter:

"1" + "1"
1 + 1
1 + int("1")

Here’s what’s going on in your code above:

  • The first statement concatenates the two strings; the quotation marks ensure the numbers are treated as strings. The result is simply "11".
  • The second statement adds the two numbers together as integers with 2 as the result.
  • The final statement adds an integer to a string that has been converted to an integer, so it also returns 2.

If Statements

If statements check whether a conditional is true, and if so, they execute a block of code. Conditionals are usually in the form of valueoperatorvalue and usually compare two values.

For example, you could evaluate whether a variable is equal to zero with the expression x == 0, where == is the equality operator.

Here are some common comparisons in Python:

a == b: #Checks if a and b are equal
a != b: #Checks if a and b are not equal
a > b:  #Checks if a is greater than b
a < b:  #Checks if a is less than b
a >= b: #Checks if a is greater than or equal to b
a <= b: #Checks if a is less than or equal to b

If statements take the following form:

if conditional:
    do_statements_here

Note how the do_statements_here line is indented. This is how you declare code blocks in Python. It’s imperative that every line in a code block is indented by the same number of tabs or spaces as all other lines in the code block; this is a rule enforced by the language itself. In other words, don’t mix tabs and spaces!

To create an if statement, type the following into your interpreter:

pyblock

You’ll be greeted by the cryptic prompt ...; this indicates the interpreter is waiting for your code block.

Press Tab, and type the second line as follows:

pyblocktab

Press Enter one more time and your cursor returns to the left side of your console. To add another line to the conditional block, just hit Tab.

If you’re done entering lines, press Enter to tell the interpreter that your code block is complete.

pyblockcomplete

Take a look at the example below:

x = 10
y = 10
if x == 10:
    print "x equals 10!"
if x == y:
    print "x equals y!"

The first if statement checks whether x is equal to 10; if so, it prints out x equals 10!. The other if statement checks whether x and y; if so, it prints "x equals y!".

For Loops

For loops in Python loop through items in a list and set a variable to the current item in the list. A list is a collection of just about anything!

Type in the following code, indenting as shown below:

for x in range(10):
    print x

In this example, range(10) generates a list of numbers from 0 to 9. The for loop, in turn, sets x to each number in the range.

Just like an if statement, a for loop executes everything indented beneath it. In the above example, the indented code block only contains a single statement.

Since print is called ten times, once for each item in the list, the program prints the numbers from 0 to 9.

Functions

Functions are reusable blocks of code that perform specific tasks. For example, you could write a function to add two numbers together, or print out a string.

You define and call a function as shown in the example below:

def hello():
    print "Hi"
for x in range(3):
    hello()

Can you guess what the output of this program is before you run it? Check your answer below:

Solution Inside SelectShow>

The indented code defines the statements which run when you call the function. Since print "Hi" is the only indented line under the function declaration, it’s the only line that executes when the function is called — not the other lines below.

You call a function by typing the function name followed by open and closed parentheses. As shown earlier, hello() calls the function you declared above.

Functions are a little like walled gardens: they can’t see anything outside of their own little area. This is known as variable scope. If you want a function to work with any outside data, you’ll need to pass that data to the function.

This is accomplished using arguments — and no, functions don’t argue with each other! :]

An argument is a variable that you pass to a function; the function can then access the value of that variable inside its walls.

You declare a function with arguments as follows:

def add(a, b):
    print a + b

The above function defines two arguments, a and b, separated by commas between the parentheses. When you call the function, the interpreter sets the value of a and b to the value of the variables you pass in.

Take a look at the example below:

def add(a, b):
    print a + b
add(1,2) # prints 3!

In the example above, the statement add(1,2) sets a and b to 1 and 2, respectively. The function then prints out the sum of the two numbers you passed in.

The above example prints out the result of the calculation — but what if you wanted to do something with the result of that calculation? What if you wanted to add other values to the result of the function?

To do this, you’ll need to add a return statement to your function.

Consider the code below:

def add(a,b):
    return a + b
print add(2, 2) + 1

In the above example, your function adds the two numbers as before, but the return statement then passes the sum of the two numbers back to the calling statement.

That means the print statement above takes the value returned by add(2,2) and adds it to 1, which will give the final value of 5.

While Loops

While loops are similar to for loops. For loops continue until you reach the end of a list, but while loops will repeat indefinitely until a given condition evaluates to False.

The general structure of a while loop is shown below:

while (conditional):
    run_statement

Generally, the conditional variable in a while loop is updated as the loop runs.

To see this in action, type the following into your interpreter:

x = 0
while x < 10:
    print x
    x += 1

This behaves the same as the for loop example above, but uses a while loop instead.

Here’s what the code above does:

  1. Sets x = 0
  2. Checks if x < 10
  3. If x < 10 evaluates to True, then execute the block below. If it evaluates to False then exit the loop
  4. Print x
  5. Increment x by 1

One thing to watch out for with while loops is creating an infinite loop.

To see how an infinite loop functions, type the following code into your interpreter:

x = 0
while True:
    print x
    x += 1

All the things!

Whoa — Terminal is going pretty crazy, isn't it? Terminate your program by pressing Control+C on your keyboard.

What the heck happened there? If you look closely, you'll see that it was impossible for the while loop conditional: True, to ever evaluate to False, so the block executed as fast as the CPU could crunch numbers.

The moral of this story: always be careful when writing while loops, because infinite loops in your code are rarely considered a good thing out in the real world!

It is possible to use True as your while loop conditional, especially when you might not know how many times your loop should execute. However, you need to use a little trick to exit out of the loop.

Type the following code into your interpreter:

x = 0
while True:
    print x
    x += 1
    if x > 10:
        break

That's better! The above code prints the numbers from 0 to 10 and exits. The trick here is to use the break statement which immediately exits out of any loop. You can also use this technique if you're in the middle of a for loop and need to exit prematurely for whatever reason.

Capturing User Input

One cool thing about Python is that it's very easy to receive input in the form of text from the user. Input is any external data provided to a program, such as text or other directions which affect the behavior of a program.

Type the following code into your Python interpreter:

name = raw_input("What is your name? ")
print "Hello, " + name

The above code first asks the user for input; once the user types in their answer to the question the program assigns it to the variable name. Once that's done, the program then concatenates the string "Hello, " with the contents of the variable name.

The raw_input() function is built right into Python; it does the work of printing out the provided string to the console, captures the text input from the user, then returns the captured text as the return value of the function.

You can make a simple calculator using the above technique of capturing user input.

Type the following code into your interpreter:

a = raw_input("Number 1: ")
b = raw_input("Number 2: ")
print int(a) + int(b)

First, you capture two values input by the user and assign them to the a and b variables respectively. Then you convert the input values into integers and add them together.

Why the conversion step? Simply because raw_input() interprets all input as strings, and you want to add the integer values together.

If you didn't convert the strings to integers, what do you think would happen? That's right — the program would print out the concatenation of the two strings, which is not what you want!

Imports

Before you dig into imports, it's worthwhile introducing the Python module.

A module is a group of Python functions which you can reuse in your programs. Importing a module is the equivalent of taking the all the code from the module and putting it right into your program so you can use all of the functions whenever you want, but without cutting and pasting a single line of code!

There are lots of modules available in the Python community, but right now you'll just touch on the random module.

To import a module, type the following into your interpreter:

import random

Once the random module has been imported, you can use it like this:

print random.randint(0, 100)

This prints out a random integer between 0 and 100; pretty straightforward stuff.

You've gained a lot of knowledge by this point, enough to put together a small program that exercises everything you've learned so far!

Guessing Game Time!

Guessing Game

This is where all of your hard work learning to code Python pays off. You're going to create your very own guessing game!

First off, you'll need a better way to run programs than typing them directly into the Python interpreter, statement by statement.

To do that, you'll create a Python file.

Mac

To create a simple Python file on a Mac, type the following commands into Terminal:

$ touch guess.py
$ open -t guess.py

This creates an empty file called guess.py using the touch command, then opens that file in your default text editor using the open -t command.

Once you have some code in your Python file, you can execute your program by typing python guess.py in Terminal.

Windows

On Windows, click on the File menu in IDLE and scroll down to New File. You'll see a text editor appear where you can type in your new program.

Click the File menu again, and choose Save. Name the file guess.py and save it to whatever location you like.

To run your program, select Run\Run Module from the menu bar, like so:

IDLE will then open up the interpreter and show you the output of your program.

Game Time!

The guessing game will generate a random number, then use a loop to ask the player repeatedly for their guess. If the user guesses the number, it'll exit the loop; otherwise the program will notify the user if their guess was too high or too low and continue to ask the player for guesses until they get it right.

You'll begin by generating a random number that will be used for the player to guess.

Add the following code to the Python file you just created:

import random
 
number = random.randint(0, 100)

The above code imports the random module, then generates a random number between 0 and 100 and stores it in the variable number.

Next, you need to ask the player for their guess. Add the following code to the bottom of your program:

guess = raw_input("Guess the Number: ")

This code, as you can probably guess, asks for user input and assigns it to the variable guess. Remember, that variable is now set to a string — you'll need to convert that string to an integer.

Add the following code to your program, right after the guess statement you added above:

guess_int = int(guess)

This code sets the variable guess_int to the integer value of the string you received from the user.

Next you need to compare the user's guess to the randomly selected number.

Add the following code to the end of your program:

if number > guess_int:
    print "Too low!"
if number < guess_int:
    print "Too high!"
if number == guess_int:
    print "You got it!"

Run your program by clicking Run\Run Module in the menu bar or entering python guess.py in Terminal; enter a number when your program prompts you. What happens?

The program stops as soon as you enter a number and it outputs the result to the screen. Whoops!

You want the program to continue looping until the person guesses correctly. You'll add this functionality by using a variable named running.

Add the following code just after the import statement:

running = True

running will be used with a while loop to control the looping of your program. When the user guesses the correct number, the program will set running to False and the while loop will stop.

Add the following code right before the statement where you ask the user for a number:

while running:
    guess = raw_input("Guess the Number: ")
    ...etc

Next, indent the remainder of the program by one level so the while loop recognizes this as the code block for the loop.

Finally, you need to add the logic that sets running to False once the user wins.

Add the following code directly after the third print statement:

if number == guess_int:
    print "You got it!"
    running = False

Make sure that the two lines below the if statement are indented by two levels.

Run your program, and try it out now. How many guesses will it take you to guess the right number?

Guess the number: 50
Too Low!
Guess the number: 75
Too Low!
Guess the number: 87
Too High!
Guess the number: 80
Too Low!
Guess the number: 82
Too Low!
Guess the number: 84
Too High!
Guess the number: 83
You Got It!

Your completed program should now look like the following:

import random
running = True
number = random.randint(0, 100)
 
while running:
    guess = raw_input("Guess the Number: ")
 
    guess_int = int(guess)
 
    if number > guess_int:
        print "Too low!"if number < guess_int:
        print "Too high!"
    if number == guess_int:
        print "You got it!"
	running = False

Congratulations — you've just written your first Python program. That wasn't so hard, was it? :]

Where to Go From Here?

Now that you've successfully completed this Python tutorial for beginners, I bet you're itching for a challenge. Try adding the following features to your program:

  • A running count of guesses
  • A bigger range of numbers to pick from
  • A computer opponent to compete against

If you are looking to make a slightly more complicated game, check out one of my other tutorials: Beginning Game Programming for Teens with Python.

If you have any comments or feedback, feel free to share them in the forum!

Programming for Teens: Beginning Python Tutorial is a post from: Ray Wenderlich

The post Programming for Teens: Beginning Python Tutorial appeared first on Ray Wenderlich.

Swift Language Highlights: An Objective-C Developer’s Perspective

$
0
0

Swift

If you were like me this Monday, you were sitting back enjoying the keynote, excited to start trying out all the new lovely APIs. And then your ears pricked up as you listened to words about a new language: Swift! It suddenly hit you that this is not an extension to Objective-C, but a completely brand new language. Maybe you were excited? Maybe you were happy? Maybe you didn’t know what to think.

Swift has surely changed the way we’re going to write iOS and Mac applications in the future. In this post, I outline some of the highlights of the Swift language, contrasting them to their counterparts in Objective-C.

Note this post is not designed to be a Swift get started guide. Apple have released a fantastic book about this, and I strongly suggest you read it. Instead, this is a discussion of some particularly cool areas to notice and play around with!

Types

The first huge thing that Swift provides is type inference. In a language that uses type inference, the programmer doesn’t need to annotate variables with type information. The compiler infers it from what value is being set to the variable. For example, the compiler can automatically set this variable to a String:

// automatically inferred
var name1 = "Matt"
// explicit typing (optional in this case)
var name2:String = "Matt"

Along with type inference, Swift brings type safety. In Swift, the compiler (in all but a few special cases) knows the full type of an object. This allows it to make some decisions about how to compile code, because it has more information at hand.

This is in stark contrast to Objective-C which is extremely dynamic in nature. In Objective-C, no type is truly known at compile time. This is in part because you can add methods to existing classes, add entirely new classes and even change the type of an instance, all at runtime.

Let’s take a look at that in some more detail. Consider the following Objective-C:

Person *matt = [[Person alloc] initWithName:@"Matt Galloway"];
[matt sayHello];

When the compiler sees the call to sayHello, it can check to see if there’s a method declared in the headers it can see on the type Person called sayHello. It can error if there isn’t one, but that’s about all it can do. This is often enough to catch the first line of bugs that you might introduce. It will catch things like typos. But because of the dynamic nature, the compiler doesn’t know if the sayHello is going to change at runtime or even necessarily even exist. It could be an optional method on a protocol, for example. (Remember all those respondsToSelector: checks?).

Because of this lack of strong typing, there is very little the compiler can do to make optimisations when calling methods in Objective-C. The method that handles dynamic dispatch is called objc_msgSend. I’m sure you’ve seen this in many a backtrace! In this function, the implementation of the selector is looked up and then jumped to. You cannot argue this doesn’t add overhead and complexity.

Now look at the same code in Swift:

var matt = Person(name:"Matt Galloway")
matt.sayHello()

In Swift, the compiler knows much more about the types in play in any method call. It knows exactly where sayHello() is defined. Because of this, it can optimise certain call sites by jumping directly to the implementation rather than having to go through dynamic dispatch. In other cases, it can use vtable style dispatch, which is far less overhead than dynamic dispatch in Objective-C. This is the kind of dispatch that C++ uses for virtual functions.

The compiler is much more helpful in Swift. It will help stop subtle type related bugs from entering your codebase. It will also make your code run faster by enabling smart optimisations.

Generics

Another huge feature of Swift is generics. If you’re familiar with C++, then you can think of these as being like templates. Because Swift is strict about types, you must declare a function to take parameters of certain types. But sometimes you have some functionality that is the same for multiple different types.

An example of this would be the often useful structure of a pair. You want a pair of values to be stored together. You could implement this in Swift for integers like so:

struct IntPair {
    let a: Int!
    let b: Int!
 
    init(a: Int, b: Int) {
        self.a = a
        self.b = b
    }
 
    func equal() -> Bool {
        return a == b
    }
}
 
let intPair = IntPair(a: 5, b: 10)
intPair.a // 5
intPair.b // 10
intPair.equal() // false

Sort of useful. But now you want this to work for floating point numbers as well. You could define a FloatPair class, but that would look awfully similar. This is where generics come in. Instead of declaring a whole new class, you could simply do this:

struct Pair<T: Equatable> {
    let a: T!
    let b: T!
 
    init(a: T, b: T) {
        self.a = a
        self.b = b
    }
 
    func equal() -> Bool {
        return a == b
    }
}
 
let pair = Pair(a: 5, b: 10)
pair.a // 5
pair.b // 10
pair.equal() // false
 
let floatPair = Pair(a: 3.14159, b: 2.0)
floatPair.a // 3.14159
floatPair.b // 2.0
floatPair.equal() // false

Pretty useful! It might seem unclear why you’d want this sort of feature at this time, but trust me: the opportunities are endless. You’ll soon start to see where you can apply these in your own code.

Containers

You’ve come to know and love NSArray, NSDictionary and their mutable counterparts. Well, now you are going to have to learn about their Swift equivalents. Fortunately, they’re pretty similar. Here is how you declare arrays and dictionaries:

let array = [1, 2, 3, 4]
let dictionary = ["dog": 1, "elephant": 2]

This should be fairly familiar to you. There’s one slight catch though. In Objective-C, arrays and dictionaries can contain any type you jolly well wish. But in Swift, arrays and dictionaries are typed. And they are typed through the use of our friend from above, generics!

The two variables above can be rewritten with their types expressed (although remember you don’t actually have to do this!) like so:

let array: Array<Int> = [1, 2, 3, 4]
let dictionary: Dictionary<String, Int> = ["dog": 1, "elephant": 2]

Notice how generics are used to define what can be stored in the container. There is also a short form for the array, which is slightly more readable, but essentially boils down to the same thing:

let array: Int[] = [1, 2, 3, 4]

Notice now that you cannot add anything to the array that isn’t of type Int. This may sound like a bad thing, but it’s incredibly useful. No longer does your API have to document what is being stored in the array it returns from a certain method or stored in a property. You can give that information right up to the compiler so that it can be smarter about error checking and optimisation described earlier.

Mutability

One interesting thing about collections in Swift is their mutability. There are no “mutable” counterparts to Array and Dictionary. Instead, you use the standard let and var. For those who haven’t read the book yet, or delved into Swift at all (and I suggest you do, ASAP!), let is used to declare a variable as constant, and var is used to declare a variable as, well, variable! let is like using const in C/C++/Objective-C.

The way this relates to collections is that collections declared using let cannot change size. That is, they cannot be appended to, or removed from. If you try to, then you get an error like so:

let array = [1, 2, 3]
array.append(4)
// error: immutable value of type 'Array<Int>' only has mutating members named 'append'

The same applies to dictionaries. This fact allows the compiler to reason about such collections and make optimisations as appropriate. If the size cannot change, then the backing store that holds the values never needs to be reallocated to accommodate new values, for example. For this reason it is good practice to always use let for collections that won’t change.

Strings

Strings in Objective-C are notoriously annoying to deal with. Even simple tasks such as concatenating lots of different values becomes tedious. Take the following example:

Person *person = ...;
 
NSMutableString *description = [[NSMutableString alloc] init];
[description appendFormat:@"%@ is %i years old.", person.name, person.age];
if (person.employer) {
  [description appendFormat:@" They work for %@.", person.employer];
} else {
  [description appendString:@" They are unemployed."];
}

This is quite tedious and contains a lot of characters that are nothing to do with the data being manipulated. The same in Swift would look like this:

var description = ""
description += "\(person.name) is \(person.age) years old."
if person.employer {
    description += " They work for \(person.employer)."
} else {
    description += " They are unemployed."
}

Much clearer! Notice the cleaner way of creating a string from a format, and you can now concatenate strings simply by using +=. No more mutable string and immutable string.

Another fantastic addition to Swift is comparison of strings. You’ll be aware that in Objective-C it is not correct to compare strings for equality using ==. Instead you should use the isEqualToString: method. This is because the former is performing pointer equality. Swift removes this level of indirection and instead leaves you being able to directly use == to compare strings. It also means that strings can be used in switch statements. More on that in the next section though.

The final piece of good news is that Swift supports the full Unicode character set natively. You can use any Unicode code-point in your strings, and even function and variable names! You can now have a function called 💩 (pile of poo!) if you want!

Another nugget of good news is there is now a builtin way to calculate the true length of a string. When it comes to the full Unicode range, string length is non-trivial to compute. You can’t just say it’s the number of bytes used to store the string in UTF8, because some characters take more than 1 byte. In Objective-C, NSString does the calculation by counting the number of UTF16, 2-byte pairs are used to store the string. But that’s not technically correct since some Unicode code-points take up two, 2-byte pairs.

Fortunately, Swift has a handy function to calculate the true number of code-points in a string. It uses the top level function called countElements(). You would use it like so:

var poos = "&#x1f4a9;&#x1f4a9;"
countElements(poos) // 2

It doesn’t quite work for all cases though still. It just counts the number of Unicode code-points. It doesn’t take into account special code-points that alter other characters. For example, you can put an umlaut on the previous character. In that case, countElements() would return 2 for the pair, even though it looks like just 1 character. Like so:

var eUmlaut = "e\u0308" // ë
countElements(eUmlaut) // 2

All that said, I think you’ll agree that strings are pretty awesome in Swift!

Switch statements

The final thing I want to call out in this brief introduction to Swift is the switch statement. It has been drastically improved in Swift over its Objective-C counterpart. This is an interesting one, because it’s something that couldn’t have been added on to Objective-C without breaking the fundamental truth that Objective-C is a strict superset of C.

The first exciting feature is switching on strings. This is something that you may have wanted to do before, but couldn’t. To “switch” on strings in Objective-C you had to use lots of if-statements with isEqualToString: like so:

if ([person.name isEqualToString:@"Matt Galloway"]) {
  NSLog(@"Author of an interesting Swift article");
} else if ([person.name isEqualToString:@"Ray Wenderlich"]) {
  NSLog(@"Has a great website");
} else if ([person.name isEqualToString:@"Tim Cook"]) {
  NSLog(@"CEO of Apple Inc.");
} else {
  NSLog(@"Someone else);
}

This is not particularly readable. It’s also a lot of typing. The same in Swift looks like this:

switch person.name {
  case "Matt Galloway":
    println("Author of an interesting Swift article")
  case "Ray Wenderlich":
    println("Has a great website")
  case "Tim Cook":
    println("CEO of Apple Inc.")
  default:
    println("Someone else")
}

Aside from the switching on a string, notice something interesting here. There are no breaks in sight. That’s because cases in switches no longer fall through to the next one. No more accidentally falling through bugs!

Now the next switch statement may very well blow your mind, so be prepared!

switch i {
case 0, 1, 2:
    println("Small")
case 3...7:
    println("Medium")
case 8..10:
    println("Large")
case let ii where i % 2 == 0:
    println("Even")
case let ii where i % 2 == 1:
    println("Odd")
default:
    break
}

First up, there is now a break. This is because switches need to be exhaustive, i.e. they need to handle all cases now. In this case, we want the default to do nothing, so a break is added to declare the intentions that nothing should happen.

The next interesting thing is the ... and .. that you see in there. These are new operators and are used to define ranges. The former, defines a range up to and including the right hand number. The latter defines a range up to and excluding the right hand number. These are incredibly useful.

The last thing is the ability to define a case as a calculation of the input. In this case, if the value doesn’t match anything from zero to ten, it prints “Even” if it’s even and “Odd” if it’s odd. Magic!

Where To Go From Here?

This has hopefully given you a taste of the Swift language and what wonderful gems there are in there. But there’s far more! I encourage you to go and read the Apple book, and other Apple documentation that will help you learn this new language. You’re going to have to do it sooner or later!

We’d love to hear what you think of the Swift language so far, or if there are any cool highlights you’re excited about. Please chime in with your thoughts below!

Swift Language Highlights: An Objective-C Developer’s Perspective is a post from: Ray Wenderlich

The post Swift Language Highlights: An Objective-C Developer’s Perspective appeared first on Ray Wenderlich.

Video Tutorial: Saving Data in iOS Part 2: Using The Filemanager

Arduino Tutorial: Creating Pong

$
0
0
Learn how to create a pong game with an Arduino and an LCD!

Learn how to create a pong game with an Arduino and an LCD

If you’re a programmer with an interest in electronics, playing around with an Arduino Uno is a great way to learn.

We’ve had several tutorials on the Arduino on this site in our past, that cover topics such as using a button, creating a traffic light, and even making a temperature sensor.

If you’ve done those and are looking for more, we have a great tutorial for you!

In this tutorial you will create a fully functional 2-player Pong game, and learn about more advanced techniques like reading a data sheet, soldering, and more.

So, sit back, grab a nice refreshing beverage and get ready to build your very own console and Pong game! :]

Prerequisites

This tutorial will make use of the following topics:

  • C programming language
  • Electronic circuits
  • Arduino platform (software and hardware)
  • Soldering

Technically, you can follow this tutorial without any knowledge about these topics. Understanding any or all of these, however, will make things much easier for you, and help with building your own little console and pong game.

Note: Soldering irons get incredibly hot and can cause severe burns! Be very, very careful when you turn on your soldering iron and throughout the process. Make sure you are not around flammable materials or working on a wooden surface. Finally, when you finish soldering, let the iron cool down before storing it away.

Materials required

Since this tutorial will focus not only on writing the game for Arduino but also on building your own little console, you will need some materials:
Pong Materials

Some of the materials required come with the Sparkfun Inventor’s Kit, at $99.95. The kit includes the potentiometer, jumper wires, 1 breadboard, USB cable, 2 of the 4 buttons you will need, and many other cool pieces of hardware that will allow you to make other projects and continue learning with the included tutorials and booklet. The full list of items you need to complete this tutorial are as follows:

  • Arduino Uno R3 (Quantity: 1) at $29.95 [included in Sparkfun Inventor's Kit]. This is the core piece of your console/circuit. It’s the brains of your project and what you will connect everything to.
    ArduinoUno
  • 128×64 Graphic LCD (Quantity: 1) at $19.95. This is the screen you will use to draw everything and to be able to visualize your game. This tutorial uses a display based on the JHD12864E model, but the library you’ll be using will support several models from many different brands, including the KS0108 and JHD12864H models.
    Matrix LCD
  • 30-row breadboard (Quantity: 2) at $4.95 each [one is included in Sparkfun Inventor's Kit]. The breadboards are where you connect each component to interact together; You will be connecting the LCD for displaying the game, your buttons for user input, the potentiometer for controlling the LCD’s contrast, and more. Here’s what the breadboard looks like:
    30-row Breadboard
  • Male-to-male jumper wire 30-pack (Quantity: 2) at $4.95 [one is included in Sparkfun Inventor's Kit]. Jumper wires are what you will use to connect things between your breadboards and the Arduino pins.
    Jumper Wires
  • Jumper wire kit (Quantity: 1) at $6.95. These smaller, fixed-size jumper wires are excellent for jumps within your breadboards without having cables clutter everything. They are also colored so it helps to determine what each one is doing.
    Jumper Wire Kit
  • Break away headers – machine pin (Quantity: 1) at $2.95. The break away pins will be soldered into the LCD to properly connect the LCD to a breadboard.
    Breakaway pins
  • 10K potentiometer (Quantity: 1) at $0.95 [included in Sparkfun Inventor's Kit]. The potentiometer will control the contrast of the LCD.
    Potentiometer
  • Push button (Quantity: 4) at $0.35 each [two included in Sparkfun Inventor's Kit]. The push buttons will be used for user input, as up/down buttons for each player’s pong paddle.
    Push Button
  • USB cable A to B (Quantity: 1) at $3.95 [included in Sparkfun Inventor's Kit]. This is the cable you use to connect the Arduino board to your computer in order to upload sketches and provide it with power.
    USB Cable
  • Soldering iron (Quantity: 1) at $9.95. You will use the soldering iron to solder the break away header pins to the LCD holes. This will give you good, solid connection points out of the LCD and will also allow for easy connections to your breadboard.
    Soldering Iron
  • Lead-free solder wire rosin core spool (Quantity: 1) at $7.95. Solder is a metal combination that very easily melts under heat and is fantastic for soldering together components. The rosin core is used to keep the connections clean during the soldering process and facilitates the bond between the metals and the solder. Read more about rosin core here.
    Rosin Spool
  • Digital multimeter (Optional) (Quantity: 1) at $14.95. A multimeter will help you measure DC voltage, resistance, and more.
    Multimeter

In total, the cost of all the materials (assuming you buy all of them from scratch) is approximately $104 without a multimeter and $119 with one. If you buy things with the Sparkfun Inventor’s Kit, it will cost about $54 extra ($158 without / $173 with the multimeter).

This may seem rather pricey, but remember you can use these materials more than once. Apart from the header pins (only 20 of them) that you will solder to the LCD, or the solder spool, everything is going to be useful for many, if not all of your projects.

Setting up your dev environment

In order to work with Arduino and upload your sketches (the name of a program in Arduino), go to the Arduino downloads page and get the latest version of the IDE for your operating system. If you are using an Arduino Due or Yún then you will need to download the latest beta version 1.5 or above.

Once downloaded, put the Arduino app in your Applications folder and run it. You may be prompted to install Java, go ahead and do so as it’s required to run the Arduino IDE.

Having run the IDE at least once, you will have a new folder in your user Documents directory named Arduino:
Arduino Folder

Writing your own code to draw to the LCD would be very time consuming. When you write an Android or iOS app you don’t code everything from scratch; you get APIs for data structures, drawing to the screen, sound, and more. Similarly, Arduino has a vast array of libraries (first and third party) that you can use for your projects.

A library called GLCD, which you can acquire here, provides you with easy-to-use functions to draw to many models and types of LCD displays.

Go ahead and download the source for GLCD and locate the folder. Drag the newly downloaded folder for GLCD and put it inside ~/Documents/Arduino/libraries. This is how you install additional libraries for Arduino:
GLCD Installed

Note: I made the GLCD folder in my Arduino libraries an all uppercase name. This is just so it shows up neatly underneath the Sketch menu option. You can use whichever naming convention you prefer.

Relaunch the Arduino IDE and in the menu bar go to Sketch/Import Library…, at the very bottom (underneath the “Contributed” header) you will see GLCD listed:
GLCD Menu Option

With that, your development environment is ready. Yaaaay! :]

But before you can do anything you have to solder some header pins to the LCD and connect everything to the Arduino.

Connect All The Things

Soldering the LCD

Soldering is not that difficult, and once you start it’s really quite addicting and fun :]

As mentioned previously though, it’s quite dangerous and a soldering iron can give you severe burns if you are not careful. Because soldering is not something that can be easily taught in pictures (specially trying to soldering something while taking a photo with a cell phone), here’s a cool YouTube video that will show you how to do it:

Note: if you can’t see the video above then it’s probably because it requires Flash installed. If you don’t like to have Flash installed, use the Chrome browser to view the video by visiting this link.

Soldering requires practice and is not something that can be mastered in just a couple of minutes or by watching a tutorial. Try practicing by soldering together some jumper wires, the inner wires of an ethernet cable, LEDs, resistors, or other simple items like header pins.

Once you are comfortable with using a soldering iron, break off 20 male-to-male header pins:
Header Pins

Take the smaller or thinner end of the header pins depending on the type you have and put them through the LCD’s holes from the bottom. Next, solder the header pins to the LCD:
Soldered LCD

As you can see, these are not the solder joints of an expert :]. Once you’re done you will probably feel like this:
Soldering Meme

Don’t worry, practice makes perfect. The important things to do here are to be very careful avoiding getting burns or inhaling any of the fumes from the solder, and to make sure each pin is connected to the corresponding hole of the LCD and only to one hole. If not, you will have a short circuit in the LCD and things will not work correctly.

Connecting the LCD

Now that you have the LCD soldered to the header pins, it’s time to start connecting it to your Arduino board. Before getting started it’s a good idea to find the data sheet for your LCD’s model. In my case, and assuming you are using an LCD based on the 12864E model, you will find a document like the one found here.

Don’t worry if this document seems a bit daunting. You only have to understand what each pin corresponds to, how to connect it to the Arduino Uno, and some basic information like the electrical characteristics. How about you start with the latter:

Electrical Characteristics

The table above shows the parameter for the LCD, its symbol, the unit it uses, and the minimum, average and maximum values for each particular parameter. It’s very good to pay attention to this as you don’t want to damage any of your equipment. If you were to supply the LCD with a value that exceeds the maximum for a given parameter you will likely permanently damage it.

For now, you don’t have to understand every single value shown here (or everything in the data sheet for that matter), but do take this into account for future projects that you build on your own. If there is something that you are not sure about you can always search for an answer online, or ask in the Arduino (or other) forums.

Now take a look at the LCD’s dimensions section:
LCD Dimensions

This is shown as if looking at the LCD from the top. The right-most pin is pin number 1, and the left-most pin is pin number 20 for the 12864E model (reversed for example on the 12864H model). This is of importance when looking at the pin values and connecting them to the Arduino board. Here are the LCD’s interface pin connections for the 12864E:
Interface Pin Connections

The LCD is divided into two, 64×64 sections, this is why there are pins for chip select (to draw on the left side of the screen or the right). There are also data pins to control the data that is drawn to the screen, pins for the LCD’s backlight, contrast, ground and voltage input, reset, and a couple others.

But where does each pin for the LCD go into the Arduino board? For that, you need to take a look at the GLCD documentation, available here. Scroll down a little bit in the document and you’ll see a table similar to the one below:
Panel Table

The table lists the pins for several different Arduino boards, in your case you want to use the left-most column titled Arduino Pins unless you’re using a board different than the Arduino Uno. Moving on you will notice a column with comments where appropriate and three columns for Panels A, B, and C.

These columns are what you need to focus on for now. Depending on your display type and what the data sheet says, your panel may need to be connected differently.

As a challenge, try and find what type of panel connection you need to use for an LCD based on the 12864E model.

Solution Inside: Solution SelectShow>

Once you’ve determined what panel type you need to use for your connection, scroll down a bit further in the GLCD documentation and look at the graph showing how to connect the LCD panel to the Arduino board. Here’s the graph for panel type B:
Panel B Connections

You’re now equipped with all the information you need to successfully connect the LCD. Grab a breadboard with at least 30 rows and connect the LCD as shown:
LCD To Breadboard

Notice how pin 1 in the LCD is connected to row 1 on the breadboard. This is not necessary but it will make it easier to know what pins you’re connecting the jumper wires to. Grab a pair of jumper wires and connect the positive rail on the breadboard (shown in red above) to the 5V output on the Arduino, and the negative rail (shown in blue above) to the Arduino’s ground.

For the rest of the connections, make sure to reference the GLCD panel chart from earlier to identify which pin on your LCD corresponds with the instruction listed below. LCD pins are referenced in bold and use the naming convention found in the Function column of the same chart:

On the other end of the breadboard’s positive and negative input rails, jump a couple of wires from the +5 volt row of your LCD to the +5V rail of the breadboard and from the Gnd row to the ground rail:
LCD Connections 1 And 2

Connect the Reset row of the LCD to the Arduino’s Reset pin:
LCD To Reset

Connect the CSEL1 and CSEL2 rows to the A0 and A1 pins on the Arduino, respectively:
Chip Select Pins

Now connect the Data lines (D0D7) as follows:

  • D0 to pin 8
  • D1 to pin 9
  • D2 to pin 10
  • D3 to pin 11
  • D4 to pin 4
  • D5 to pin 5
  • D6 to pin 6
  • D7 to pin 7

Pin 7 to Pin 14

Connect a jumper wire from the Backlight Gnd row to the ground rail:
LCD Pin 20

Now connect the R_W row to pin A2, D_I row to pin A3, and EN row to pin A4:
Pins A2 To A4

Adding the potentiometer

Doing good so far :] just a few more connections and you’ll be ready to test your LCD.
Doin Good

Time to step back for a minute as you’re about to connect a potentiometer (commonly referred to as ‘pot’) to control the LCD’s contrast. You’ll be needing a 10k potentiometer. Potentiometers can come in many different shapes so don’t worry if yours looks different. What’s important is the value since, depending on the resistance, you don’t want to send too much or too little voltage to the LCD’s contrast pin.

As a challenge, try to find what each pin on the potentiometer does and what they correspond to.

Solution Inside: Solution SelectShow>

Here’s what the potentiometer looks like:
Potentiometer Pins

The yellow arrow indicates the corner with a ridge and circle on the potentiometer to show you what each pin does. As you can see there’s a pin you connect to ground, one for voltage input and one for the output voltage. If you have a different potentiometer, or want to learn more about them, you can find a cool guide on connecting potentiometers here.

Testing the potentiometer (Optional)

If you have a multimeter, it’s always good practice to test out your components by comparing their real world values to the values you expect. If you don’t have one, feel free to skip ahead to the section Connecting the potentiometer.

To measure the resistance of your potentiometer and to ensure that it’s 10k Ohms, take out your multimeter and set it to measure resistance. Make sure you set it to a value larger than 10k so you get an accurate reading. This is how you connect both legs of the multimeter to the potentiometer:
Multimeter To Pot

You connect the negative and positive pins of the multimeter to the in and out pins of the potentiometer, respectively. The Yellow arrow is there to indicate the order of the legs, as previously shown.

Turn the pot all the way down and get a measurement, then all the way up and get that measurement:
Pot To Multimeter

The left side shows the value with the pot turned all the way down, and the right side shows the value with the pot turned all the way up. Notice how the multimeter is set to measure up to 20K Ohms, which means that the 10.12 value means 10.12K Ohms (approximately).

Resistors and potentiometers have a percentage by which their resistance can vary. You can usually buy more expensive hardware to reduce the variation, if you so desire, but for this scenario a small change like 120 ohms will not affect your circuit.

Connecting the potentiometer

Having learned about potentiometers, how to measure their resistance value, and what each pin does, it’s time to put your 10K pot to use in the circuit. Go ahead and connect the potentiometer to the breadboard next to your LCD:

Pot To Breadboard

Connect a jumper wire from the negative rail of the breadboard (ground) to the ground pin of the pot:
Pot To Ground

Now connect a jumper wire from the input pin of the pot to the Contrast in row of the LCD, and one from the output pin of the pot to the Contrast out row:
Potentiometer Connections

This will let you control the contrast of your LCD’s display by simply turning the knob in the potentiometer. Pretty cool, huh?

Finishing the LCD’s connections

Finally, and to complete the connections to the LCD, connect a jumper wire from the 3.3V output on the Arduino Uno to the Backlight +5 row of the LCD.
LCD Row 19

Why are you connecting the LCD’s sidelight voltage input to 3.3 volts when the electrical characteristics previously stated that the typical voltage is 4.2V?

Well, the maximum voltage is 4.6V and even after all the connections you’ve made the LCD will probably be receiving close to 5V. A jump from 4.6V to 5V may not seem like much but it could damage your LCD in the long run. It’s always very important to pay attention to the data sheet and the maximum voltage, current, and power that a component can support.

If you didn’t do this, you would need to get a resistor to lower the voltage to 4.6V or lower, and you may not have one handy. By sending 3.3V to the LCD’s sidelight panel you not only avoid damaging your LCD, but you also avoid having to use a resistor. And the end result works well, your LCD has more than enough voltage to shine very bright should you want to play without any lights turned on :].

Testing the LCD connection to Arduino

Hurray! You’ve successfully connected the LCD to your Arduino board. It was quite a lengthy process but you have learned about the electrical characteristics of an electronic component, how potentiometers work, some nice tips about voltage and making sure your devices don’t get damaged, and more!

Having set everything up, it’s time to test your connection. Fortunately the GLCD library has some examples and templates that you can upload to your Arduino in order to test everything’s working correctly. Open the Arduino IDE and go to File\Examples\GLCD\GLCDdemo:
GLCD Demo Menus

Now it’s time to upload the sketch. Connect the USB cable to your Arduino and to your computer. Make sure the correct model for your board is selected under Tools\Board and that the Serial port under Tools\Serial is using the USB port you connected your Arduino to. With that ready, go to File\Upload or hit Command+U.

Wait a few seconds for the sketch to upload and behold your awesome little console starting to take shape.
GLCD Demo

In OS X Mavericks (10.9), Apple seems to have changed the USB drivers and this may cause conflicts when uploading a sketch to Arduino. There’s a thread on the Arduino forums that proposes uninstalling and re-installing the previous drivers when running OS X Mavericks.

You may not like tampering with your default install of OS X or modifying any of its drivers or inner workings. If that’s the case, one solution which often works is to turn on verbose output during compilation and upload, by going to Arduino\Preferences, and hitting the Arduino Uno’s reset button right before the sketch begins to upload.
Verbose Output

If you see a line with something like this: avrdude: stk500_recv(): programmer is not responding then uploading has failed, and what usually did the trick for me was unplugging the USB cable from the computer and attempting to upload using the “reset” trick again. It’s tedious, yes, but let’s hope Arduino has a solution for this soon.

Connections for user input

This Is Tinkering

Yay! Yet another milestone on what will eventually become your own little gaming console :]

So now that you have the LCD working, you need to detect user input in order to be able to control the pong paddles. To do this you will use 4 push buttons (one pair for each player) and correctly detect collisions against the top or bottom of the screen.

Time to make some more connections. But first, take a look at the push buttons you’ll use:
Push Button

There are many different types of push buttons. In this case the image above shows a push button with 4 pins, and there are orange circles around two pairs of pins. Each pair of legs are connected, so it doesn’t matter which one you connect your cables to. The important thing is making sure you are connecting a wire to one of the legs of each pair.

Above the button notice an image showing the state of the push button when it’s not pressed. When the button is pushed down you allow electrical flow from one end to the other. This is how you can detect whether a button is pushed down or not, and this is how you will know when to move a player’s paddle.

Take out another breadboard, preferably another 30-row board, and connect your push buttons along with some jumper wires as shown below:
027

Their purpose are as follows:

  • Red – Simply pass the ground voltage from one side of the breadboard to the other in order to avoid tons of cables that would make it uncomfortable to play.
  • Orange and Yellow – Connect the ground voltage to one set of legs on each of the push buttons.
  • Gray – Will be connected to the input pins on the Arduino. The reason why this jump is made is so that players can comfortably push the buttons without any cables getting in their way.

Now, you may be wondering why you connect the push buttons to an input pin in the Arduino and then to ground, when the image above shows you that you need to pass electricity to the button in order to detect when it’s pressed.

If you are up for another challenge, try to find out why you do this on your own. Here’s a hint: It has to do with the digital and analog input pins in the Arduino. If you don’t want to wait then go ahead and click on the solution below.

Solution Inside: Solution SelectShow>

If you have already read the solution but want to know more about pull-up resistors, here’s a little explanation. The Arduino’s input pins typically work by receiving voltage to indicate input, this is by default using a technique called pull-down resistor. What you usually do is connect a resistor between your circuit and the input pin in order to lower the received voltage and avoid damaging the board’s input pins.

In order to avoid having to connect resistors to your circuit you can use the Arduino’s built in resistors on each pin and, thus, use a pull-up resistor. Here is information regarding the digital pins, and here is information regarding the analog pins.

What this technique does is send out +5V of output on the pin you use as a pull-up, and connect the push button to ground. When the input pin detects a value of 0V (ground) then you determine that the button has been pushed down, if the pin reads a value of +5V then the button is not being pressed.
Pullup Resistor

To learn more about pull-up resistors you can visit this link.

For this tutorial you will not use analog pins as true analog inputs, meaning you will not read analog values (the Arduino has 10 bits for each analog pin, allowing you to get integer values from 0 to 1023).

For player one connect a set of push buttons, each from the gray jumper, to pin A5 for the up button and pin 2 for the down button. For player two, connect the remaining pair of push buttons to pin 12 for the up button and pin 3 for the down button.

Connect one of the ground rails of your controller to the ground rail of your other bread board as shown in the second picture below.

This is the final circuit with all of the connections ready:
Final Pong Circuit

Drawing Player 1′s paddle

It’s finally time to write some code of your own and to get your pong game ready and working.

Note: if you like Sublime Text 2, you should try out Stino, a plugin that lets you code and run Arduino sketches form Sublime Text 2. I personally found the code highlighting and auto-completion much better, but due to the problems with Arduino on OS X Mavericks I always had to upload sketches via the main IDE.

Start by opening the Arduino IDE (or Sublime Text if you prefer to use that) and go to Sketch\Import Library…\GLCD.
Import GLCD

The following lines of code should be added at the top of your sketch:

#include <glcd.h>
#include <glcd_Buildinfo.h>
#include <glcd_Config.h>

Next declare constants for the pins corresponding to the buttons for player 1, the screen size, and paddle size, position and movement speed.

// Screen Size
const byte width           = 127;
const byte height          = 63;
 
// Variables to store the pin number for each player's up/down buttons
const byte oneUpButton     = 19; // Pin A5
const byte oneDownButton   = 2;
 
// Size of the ball and paddle
const byte paddleHeight    = 8;
 
// X position of each paddle
const byte onePaddleX      = 10;
 
// Y position of each paddle
short onePaddleY           = 28;
 
// Speed of the ball for the X and Y directions, and speed of the paddle movement vertically
short paddleSpeed          = 2;

Finally, create constants for the refresh interval (in milliseconds) and the last refresh interval, to setup a steady frame rate.

// Refresh interval at which to set our game loop 
// To avoid having the game run at different speeds depending on hardware
const int refreshInterval  = 60;
 
// Used to calculate the delta between loops for a steady frame-rate
unsigned long lastRefreshTime;

Now come the default and required Arduino functions for each sketch, setup() and loop():

/*
 * Default Arduino setup function
 */
void setup()
{
  // Player 1 buttons setup
  pinMode(oneUpButton, INPUT);
  digitalWrite(oneUpButton, HIGH); // Use built in pull-up resistor
  pinMode(oneDownButton, INPUT);
  digitalWrite(oneDownButton, HIGH); // Use built in pull-up resistor
 
  // Initialize the library to draw dark pixels on a light background
  GLCD.Init();
}
 
/*
 * Default Arduino loop function
 */
void loop()
{  
  unsigned long now = millis();
 
  if ((now - lastRefreshTime) > refreshInterval)
  {    
    checkInput();
    draw();
 
    lastRefreshTime = now;
  }
}

setup sets the pins for the paddles for player 1 to input. You also call digitalWrite with a value of HIGH for each pin to activate the pull-up resistors that you read about earlier causing each of the pins corresponding to player 1 to output +5V instead of the default 0V.

In addition, setup calls GLCD.Init() to initialize the display in its default draw mode; dark pixels on a light background. You can read more about the functions of GLCD in the documentation found here.

loop gets the milliseconds since the Arduino board began running and stores the value in a variable called now. Then, a check is performed to see if the refresh interval (acquired by subtracting the current time against the last refresh time) is greater than the refresh interval you defined earlier. If so then you call a pair of functions to check for input, and draw to the screen.

You also set the value of lastRefreshTime to now, in order to correctly check the refresh interval the next time loop gets called.

Time to write each of the functions called inside the loop’s if statement:

/*
 * Checks for user input
 */
void checkInput()
{
  // Get the state of each push button corresponding to player 1
  bool oneUpState = !digitalRead(oneUpButton);
  bool oneDownState = !digitalRead(oneDownButton);
 
  // Small delay to cleanup and improve the readings
  delay(1);
 
  if (oneDownState)
  {
    // Move player 1’s paddle down
    onePaddleY += paddleSpeed;
 
    // If the paddle is outside of the screen, move it back in
    if (onePaddleY >= height - paddleHeight)
    {
      onePaddleY = height - paddleHeight;
    }
  }
  else if (oneUpState)
  {
    // Move player 1’s paddle up
    onePaddleY -= paddleSpeed;
 
    // If the paddle is outside of the screen, move it back in
    if (onePaddleY <= 0)
    {
      onePaddleY = 0;
    }
  }
}
 
void draw()
{
  GLCD.ClearScreen();
 
  GLCD.DrawVLine(onePaddleX, onePaddleY, paddleHeight);
}

checkInput gets a boolean value with the state of each button. You negate the value read because you are using a pull-up resistor, so when digitalRead returns 0 then the button is being pushed down.

Afterwards there’s a small, 1 millisecond delay to cleanup the readings and then a check is made to see if the down button is being pushed. If so then you update the Y position of the paddle and check for collisions against the screen. The logic used here is pretty straightforward so you shouldn’t have any trouble understanding it. The same is done for when the up button is pushed.

draw first clears the screen so there are no remaining pixels or artifacts from your previous frame and then calls DrawVLine with the X and Y positions, and the height of the vertical line to draw. Notice inside both methods how you make good use of the constants previously declared at the top of the header file.

Go ahead and upload the sketch to your Arduino and push the up and down buttons.
Left Paddle

Hurray! the paddle should be moving and correctly colliding against the top and bottom edges of the screen. Awesome job :]

Drawing Player 2′s paddle

Having looked at how to draw the paddle for player 1, check for input, and correctly detect for collisions against the screen, you are now ready to do the same for player 2.

As a challenge, try to do all of this without looking at the resulting code. Again, it shouldn’t be too difficult because almost all of the code for player 1 is reusable for player 2.

If you prefer to look at the solution or get stuck then go ahead and take a peek below.

Start by adding some constants for player 2 at the top of the file:

// Variables to store the pin number for each player's up/down buttons
const byte oneUpButton     = 19; // Pin A5
const byte oneDownButton   = 2;
const byte twoUpButton     = 12; // For Player 2
const byte twoDownButton   = 3;  // For Player 2
 
// X position of each paddle
const byte onePaddleX      = 10;
const byte twoPaddleX      = 118; // For Player 2
 
// Y position of each paddle
short onePaddleY           = 28;
short twoPaddleY           = 28;  // For Player 2

The bytes to store the pin number for player 2 correspond to the connections you made earlier for the buttons. The X position of the paddle for player 2 is all the way to the right with the same amount of spacing between the screen and the paddle. Finally, the initial Y position of the paddle for player 2 is the same as that of player 1.

Update draw to include a call to draw the paddle for player 2:

void draw()
{
  GLCD.ClearScreen();
 
  GLCD.DrawVLine(onePaddleX, onePaddleY, paddleHeight);
  GLCD.DrawVLine(twoPaddleX, twoPaddleY, paddleHeight); // For Player 2
}

This is, again, passing the X and Y position of the paddle for player 2, as well as the height of the paddle. You need to setup the pins to check for input for the up and down buttons corresponding to player 2. Update setup as follows:

void setup()
{
  // Player 1 buttons setup
  pinMode(oneUpButton, INPUT);
  digitalWrite(oneUpButton, HIGH); // Use built in pull-up resistor
  pinMode(oneDownButton, INPUT);
  digitalWrite(oneDownButton, HIGH); // Use built in pull-up resistor
 
  // Player 2 buttons setup
  pinMode(twoUpButton, INPUT);
  digitalWrite(twoUpButton, HIGH); // Use built in pull-up resistor
  pinMode(twoDownButton, INPUT);
  digitalWrite(twoDownButton, HIGH); // Use built in pull-up resistor
 
  // Initialize the library to draw dark pixels on a light background
  GLCD.Init();
}

Once again you set the mode of each pin to INPUT and then call digitalWrite on each pin with a value of HIGH, to active the pull-up resistor. Now update checkInput as shown:

void checkInput()
{
  // Get the state of each push button corresponding to player 1
  bool oneUpState = !digitalRead(oneUpButton);
  bool oneDownState = !digitalRead(oneDownButton);
 
  // Get the state of each push button corresponding to player 2
  bool twoUpState = !digitalRead(twoUpButton); 
  bool twoDownState = !digitalRead(twoDownButton);
 
  // Small delay to cleanup and improve the readings
  delay(1);
  ...
  // Code to check collision for player 1's paddle
  ...
 
  if (twoDownState)
  {
    twoPaddleY += paddleSpeed;
 
    if (twoPaddleY >= height - paddleHeight)
    {
      twoPaddleY = height - paddleHeight;
    }
  }
  else if (twoUpState)
  {
    twoPaddleY -= paddleSpeed;
 
    if (twoPaddleY <= 0)
    {
      twoPaddleY = 0;
    }
  }
}

You get the input for the up and down button for player two and then check for collisions against the top and bottom of the screen. The logic is the same as player 1 except tweaked to update the y position of player 2′s paddle.

Upload the sketch to your Arduino and push the up and down buttons for player 2.
Right Paddle

Congrats :] you’re almost done, all that remains is the ball and its collisions.

Coding the ball and collision detection

Pong Is Coming

To kick off the final portion of the tutorial, and to make the complete pong game with the ball and collisions, add the following constants and variables at the top of the header file:

// Size of the ball and paddle
const byte paddleHeight    = 8;
const byte ballSize        = 2;  // Size of the ball
const byte ballPadding     = 1;  // Padding because GLCD adds an extra pixel to the size you set the ball to
 
// X and Y position of the ball
short ballX                = 63;
short ballY                = 31;
 
// Speed of the ball for the X and Y directions, and speed of the paddle movement vertically
short ballSpeedX           = 3;  // Speed of the ball in the horizontal direction
short ballSpeedY           = 2;  // Speed of the ball in the vertical direction
short paddleSpeed          = 2;

The variables you create correspond to the ball size and some padding required when working with GLCD, the X and Y position of the ball, and the X and Y speed of the ball. You want the ball to move at different speeds because the screen is not square, it’s wider so horizontally the ball should move quicker to make the game challenging.

From there, update draw to include a call to draw the ball:

void draw()
{
  GLCD.ClearScreen();
 
  GLCD.DrawVLine(onePaddleX, onePaddleY, paddleHeight);
  GLCD.DrawVLine(twoPaddleX, twoPaddleY, paddleHeight);
 
  // Draw the ball by passing in the X and Y position, and the width and height   
  GLCD.FillRect(ballX, ballY, ballSize, ballSize);
}

The last line is what you updated in the method. It draws a filled rectangle with the set X and Y position, and with the width and height (which in this case is the same so it’s a perfectly square ball).

Add a call to two new methods inside loop:

void loop()
{  
  unsigned long now = millis();
 
  if ((now - lastRefreshTime) > refreshInterval)
  {    
    checkInput();
    checkCollisions(); // New method to check for the ball's collisions
    update();          // New method to update the position of the ball on each frame
    draw();
 
    lastRefreshTime = now;
  }
}

You add a method called checkCollisions that, as the name implies, checks for collisions between the ball and screen, and the ball and paddles. The other method is called update and is going to be in charge of updating the X and Y position of the ball in each frame. Write the code for update as follows:

/*
 * Function to update the X and Y position of the ball;
 */
void update()
{
  ballX += ballSpeedX;
  ballY += ballSpeedY;
}

On every call to update you add the X and Y speed of the ball. The speed can be positive or negative, to indicate if the vertical movement is up or down, and the horizontal movement is left or right. Move on to checkCollisions, the beefiest method of them all:

/*
 * Checks collisions between the ball and walls, and the ball and paddles
 */
void checkCollisions()
{
  // 1
  // Check vertical collisions
  if (ballSpeedY > 0)
  {
    // 2
    // Limit collision checks to the ball and bottom
    if (ballY + ballSize + ballPadding >= height)
    {
      ballY = height - ballSize - ballPadding;
 
      ballSpeedY *= -1;
    }
  }
  else
  {
    // 3
    // Limit collision checks to the ball and top
    if (ballY <= 0)
    {
      ballY = 0;
 
      ballSpeedY *= -1;
    }
  }
 
  // 4
  // Check horizontal collisions
  if (ballSpeedX > 0)
  {
    // 5
    // Limit collision checks to the ball and right edge of the screen
    if (ballX + ballSize + ballPadding > width)
    {
      reset();
    }
    else if (ballX >= twoPaddleX-ballSpeedX && (ballY - ballSize >= twoPaddleY && ballY <= twoPaddleY + paddleHeight))
    {
      ballSpeedX *= -1;
 
      ballX = twoPaddleX - ballSize - ballPadding;
 
      draw();
    }
  }
  else
  {
    // 6
    // Limit collision checks to the ball and left edge of the screen
    if (ballX < 0)
    {
      reset();
    }
    else if (ballX <= onePaddleX+ballSpeedY && (ballY - ballSize >= onePaddleY && ballY <= onePaddleY + paddleHeight))
    {
      ballSpeedX *= -1;
 
      ballX = onePaddleX + ballPadding;
 
      draw();
    }
  }
}

Let’s go over each numbered section:

  1. The first if statement checks for vertical collisions, meaning if the ball has collided with the top or bottom of the screen.
  2. If the ball’s vertical speed is positive then it’s moving down, and thus you check for collisions against the bottom portion of the screen. If a collision occurred you reset the ball’s position to right up against the screen and change the vertical speed of the ball to be negative, so it now moves up.
  3. This is the same process as before except you now check for collisions against the top of the screen. Should the ball collide with it then you reset its position and change the direction of the Y speed.
  4. Now come all the checks for horizontal collisions. Either between the ball and paddles or the ball and the screen. If the X speed is positive then the ball is moving towards the right side of the screen. This check is useful as it spares you from checking for collisions in all four scenarios. Instead you can focus your checks against the right side of the screen and the right paddle, optimizing performance.
  5. In this conditional check you verify the ball’s position against the right side of the screen. If the ball is outside of the screen then reset is called. You’ll write that method in just a second, but all it does is reset the game so you can play again without having to hit reset on your Arduino. If the ball didn’t collide against the edge of the screen then you check for collisions against the paddle. If this is the case then you change its X speed, X position, and call draw to update the screen.
  6. This is the same logic as before, except now you are first checking for collisions against the left side of the screen and then left paddle.

Last but not least, write the code for reset as follows:

/*
 * Resets the paddles and ball to their initial state should either player loose
 */
void reset()
{
  // Reset the game to the initial state;
  ballX = 63;
  ballY = 31;
  onePaddleY = 28;
  twoPaddleY = 28;
  ballSpeedX = 3;
  ballSpeedY = 2;
 
  draw();
 
  delay(3000);
}

This reset’s the ball’s X and Y position, the X and Y speed, and also the paddle’s Y position. Afterwards you call draw to re-draw everything on screen and delay execution of your program for 3 seconds (3000 milliseconds) in order for players to get ready for the next round.

Upload your sketch one last time and give your pong game a test.
Final Pong

GREAT SUCCESS!!! :]

You’ve done it. You have gone from having a bunch of electric components, an Arduino board, and an LCD screen, to a fully functional pong game. This is your own little console, you’ve made something akin to the first Game Boy! A huge congratulations to you! Hopefully this is the beginning of many more fun circuits and video games with Arduino for you.
I Did It

You can download the final project here. It includes the Arduino sketch along with the GLCD library, just in case.

Where to go from here?

Where can you go from here? Well, the possibilities are endless. Here are some nice ideas for you to try:

  • Add score tracking and a UI for each player
  • Add A.I. for player two so you can play alone
  • Try making a new game instead of pong
  • Try using potentiometers to control paddle movement instead of buttons

The possibilities really are endless. You basically have a Game Boy. Google around a bit and you’ll find tons of great games or sample projects that make use of LCD screens. You could build a calculator, you could make other animations, etc.

I hope you’ve enjoyed this tutorial and learned more about electronic circuits, Arduino, soldering, and everything else that you’ve done here. I also hope that this tutorial sparks more interest in you to create other electric circuits and to continue tinkering. It really is a lot of fun.

For any questions, comments or feedback please contact me via Twitter @Airjordan12345. Many thanks again among congratulations on your new game! :]

Arduino Tutorial: Creating Pong is a post from: Ray Wenderlich

The post Arduino Tutorial: Creating Pong appeared first on Ray Wenderlich.

Swift Language FAQ

$
0
0
Swift Language FAQ: Your questions answered!

Swift Language FAQ: Your questions answered!

Swift is Apple’s entirely new, modern, type-safe programming language for Cocoa development. Swift has been in development for 4 years, and was just announced this year at WWDC.

Swift takes different constructs that are loved from many languages including Objective-C, Rust, Haskell, Ruby, Python, C#, CLU and more.

Check out Matt Galloway’s recent post on some of the Swift language highlights for more details.

The syntax is much simpler and concise, which lowers the the barrier of entry to iOS development, and makes the process more delightful.

In this Swift Language FAQ, we will answer many frequently asked questions that we have seen around our forums, Twitter, email, and StackOverflow. We will also periodically update this FAQ with new questions that come along the way.

Note that some of these answers are opinions or speculation, so take them with a grain of salt. We’d also like to hear your opinions/comments, and we will update this FAQ appropriately based on your feedback.

The Basics

I’m a beginner. Should I learn Objective-C, Swift, or both?

In our opinion, it depends if you’re planning on working with another iOS company, or as an indie.

  • If with an iOS company as a full-time iOS developer or consultant: It will be best if you learn both. This is because many iOS companies have existing code in Objective-C that you will need to understand, and some companies will not be transitioning to Swift right away. There are also tons of iOS libraries, tutorials, and sample projects written in Objective-C that you’ll need to understand. You’ll also need to learn Swift as things will be transitioning to Swift over time.
  • If you’re an indie: If you only intend to use Swift from the start, you can theoretically get by only knowing Swift. But if you can spare the time, it is still a good idea to get an understanding of Objective-C so you can make use of the huge library of existing Objective-C resources.

This answer may change over the years as the landscape develops and Swift adoption grows. Eventually, knowing Objective-C may be akin to knowing COBOL ;]

I’ve been an Objective-C developer for YEARS. Am I now a beginner?

Yes and no. If you have been developing for Apple platforms for a while you still have a huge upper hand, since you are already familiar with Xcode and the Cocoa/Cocoa Touch APIs. Since learning Xcode and the thousands of Cocoa/Cocoa Touch APIs is much more time consuming than learning Swift, you should be in good shape.

Long story short, you will feel back at home once you are familiar with writing Swift code – and you should be able to pick up Swift fairly quickly.

Will iOS 8 and OS X Yosemite apps only use Swift?

No. Apple has built Swift in such a way that it fluently interoperates with Objective-C, and vice versa! Apple has not fully converted their Objective-C APIs and Frameworks to Swift, but you can still make use of them from your Swift code.

Only time will tell, but it is likely that many iOS and OS X shops will continue to rely on Objective-C for multiple years while adopting Swift.

Does Swift work with other versions of iOS and OS X?

Yes! Xcode 6 can compile Swift code for deployment targets of iOS 7 and higher as well as OS X 10.9 and higher. Apple actually developed the WWDC app in Swift which you can download from the App Store right now!

However, keep in mind that Apple does not permit builds to be submitted to the App Store from beta versions of Xcode. Therefore you will need to wait until the final version of Xcode 6 is released before getting your Swift code in the App Store.

Is Swift meant to replace Objective-C, or supplement it?

To quote Apple, “Objective-C is not going away, both Swift and Objective-C are first class citizens for doing Cocoa and Cocoa Touch development.”

So you can still use Objective-C. However, Apple seems to be encouraging you to use Swift for any new development, while not expecting you to go back and re-write all of your Objective-C code.

Although this is pure speculation, we are guessing Apple will also be moving away from Objective-C for future Framework and API development, and some day Objective-C may even be deprecated. So, hop aboard with the rest of the raywenderlich.com Team on the Swift train :]

What is a playground?

A playground is a file where you can write code and see the results immediately. They are really great for learning Swift or new APIs, for prototyping code, or for developing algorithms.

Be careful around your kids when you say that you’re going to the playground though. As Chris LaPollo learned, this is likely to make your kids cry after you sit down at the computer instead of taking them to the park!

Is the NDA lifted yet?

This is unclear to us at the moment. Recently the iOS developer agreement terms had this new update:

Further, Apple agrees that You will not be bound by the foregoing confidentiality terms with regard to technical information about pre-release Apple Software and services disclosed by Apple at WWDC (Apple’s Worldwide Developers Conference), except that You may not post screen shots, write public reviews or redistribute any pre-release Apple Software or services.

In addition, Apple released a Swift Programming book to the public, and the iOS 8 SDK docs are public. This is a departure from previous years where information like this was not made public until the new version of iOS was released.

It’s unclear what this means as far as writing tutorials goes. There’s a strong/popular argument that says you can write tutorials as long as you don’t post screenshots. But even that is unclear to us, as Chris Adamson points out.

In our opinion, since the Swift book is public it seems the Swift language itself is fair game, but we’re not sure about screenshots from Xcode 6 or some of the other questions Chris brought up, which are pretty necessary for tutorials.

We are trying to get to the bottom of this with a clarification from Apple, and we will update this post if/when we find out.

How can I learn Swift?

There are some great resources on learning Swift already:

We’ll also be coming out with a bunch of additional resources soon – check out the next question!

Will your future books and tutorials use Swift?

The short answer – yes! We’re fully committed to helping everyone transition to Swift.

The long answer:

  • iOS 8 by Tutorials: This will be written in Swift, to help everyone transition to this new language. We will also be providing the sample projects in Objective-C for those who are not quite ready to transition to Swift, and to aid those who wish to compare the two languages.
  • iOS Games by Tutorials: We will also be updating iOS Games by Tutorials to Swift – along with another major exciting update/change which we will announce soon.
  • Written tutorials: We will be using Swift in our future written tutorials once the NDA is clearly lifted. We will also be updating many of our older written tutorials to Swift. More on this later.
  • Video tutorials: We’ll be having a lot of video tutorials on Swift/iOS 8 soon, and also updating many of our video tutorials to Swift!
  • Some surprises…: We also have a few surprises up our sleeve – stay tuned! :]

Diving Right In

Is there anything that Swift can do that Objective-C can’t, and vice-versa?

Yes! Swift is a modern language that introduces many things that Objective-C does not support. Some of the big things include namespacing, optionals, tuples, generics, type inference and many more.

Objective-C also has some “features” that are not available in Swift like messaging nil.

It would be in your best interest to read the Using Swift with Cocoa and Objective-C Guide by Apple for more details – after reading this post of course!

Are there any APIs that don’t work with Swift?

At the time of writing this post, I am not aware of any. There are however some caveats on how to move things between Objective-C and Swift APIs. Here are some examples:

  • When an Objective-C API returns an id, Swift will receive AnyObject.
  • When an Objective-C API returns nil, Swift will receive an Optional set to the value NONE which is Swift’s way of saying a variable is nil. Because Swift variables must always contain a value, it uses the Optional enum for any object returned from an Objective-C API being that there is no guarantee that an Objective-C method won’t return nil.
  • When an Objective-C API returns a collection it will be typed to AnyObject due to the inability to infer what type an NSArray or NSDictionary stores. It is a good practice to downcast your collections when they are returned based on what you know of the API. Consider an Objective-C method that returns an array of NSString instances. Because you know that the returned array contains strings, you can safely downcast in the following manner.
    let fruits : AnyObject[] = // some Objective-C API that returns NSArray of NSStrings
     
    for fruit in fruits as String[] {
        println(fruit)
    }
  • When a Swift API returns a Tuple, Objective-C will receive… nothing! Since tuples are not supported in Objective-C, the method won’t be available to Objective-C code. There are a number of Swift constructs that Objective-C cannot support. These include…
    • Generics
    • Tuples
    • Enumerations defined in Swift
    • Structures defined in Swift
    • Top-level functions defined in Swift
    • Global variables defined in Swift
    • Typealiases defined in Swift
    • Swift-style variadics
    • Nested types
    • Curried functions

Where are my println() results in my Playground?

You must turn on the Assistant Editor to see your console output. Do this via View > Assistant Editor > Show Assistant Editor or by the keystroke Option + Command + Return.

Thanks to Chris LaPollo for providing insight on this one!

How do I see those cool graphs of values in Playgrounds?

You can graph the results of values over time in Playgrounds, which can be really handy for visualizing algorithms.

To do this, enter some code that produces values over time like this in a playground:

for x in 1..10 {
  x
}

In the sidebar, you’ll see something like “9 times”. Move your mouse over this line, and a + button will appear. Click this button (and make sure your Assistant Editor is open) and you should see the graph.

How do you run the REPL?

Run the following command in Terminal to tell it to use Xcode 6′s command line tools.

sudo xcode-select -s /Applications/Xcode6-Beta.app/Contents/Developer/

Then run the following to start the Swift REPL.

xcrun swift

When you are ready to exit you can type :exit or :quit. You can also use the CTRL+D keystroke.

Can you use Swift to call your own Objective-C code or a third party library? If so, how?

Yes! When you add your first .swift file to your Xcode Project you will be prompted to let Xcode create a bridging header file. In that header file you can import the Objective-C headers that you want to be visible to your Swift code.

Then, all of those classes will be available to your Swift code without further imports. You can use your custom Objective-C code with the same Swift syntax you use with system classes.

So, arrays can only contain one type of object? What if I want varied types?

In Swift you are highly encouraged to make strongly typed arrays that contain only one type of object, with syntax like this:

var goodArray: String[] = ["foo", "bar"]

That said, technically you can still create arrays that contain multiple types of objects. However, before you do this you should be asking yourself why you want to do this. In most cases it does not make the best sense and you can likely engineer your solution to be cleaner.

With that said, here’s how you can create a Swift array with varying types of objects within it by using AnyObject:

var brokenArray: AnyObject[] = ["foo", 1, 12.23, true]

Is the same true for dictionaries? Are dictionaries also strongly typed?

Yes, but again you can get around this by using AnyObject. For dictionaries it often might make sense that not all of the values in your dictionary are of the same type. Consider a JSON response from a server that is represented as a dictionary:

var employee : Dictionary<String, AnyObject> = ["FirstName" : "Larry", "LastName" : "Rodgers", "Salary" : 65_000.00]

This dictionary contains two keys with String values and one key with a Double value. Although this is achievable, you should opt to create first class model objects to represent your data rather than relying on Dictionaries when possible.

The Nitty Gritty

Is there an equivalent to id in Swift?

Yes. As mentioned above when an Objective-C API returns id Swift will substitute with AnyObject. The AnyObject type can represent an instance of any class type. There is also Any which can represent an instance of any type at all (apart from function types).

How do you do introspection in Swift? (e.g. equivalent of if ([obj isKindOfClass:[Foo class]]) { … })?

You can check the type of a variable or constant using the is keyword. The compiler is smart enough to let you know if using is would be redundant. Thanks to type safety in Swift, it is not possible to later assign a different type to the same reference, which makes this possible.

var someValue : Any?
 
someValue = "String"
 
if someValue is String {
    println("someValue is a String")
} else {
    println("someValue is something else")
}

Notice if you try to write…

var someValue = "String"
 
if someValue is String {
    println("someValue is a String")
} else {
    println("someValue is something else")
}

You will receive a compiler warning:

Playground execution failed: error: <REPL>:7:14: error: 'is' test is always true
if someValue is String {

How do you put bitshifted values inside an enum in Swift? (i.e. MyVal = 1<<5)

Unfortunately Apple has not clearly addressed this yet. There are some rumors floating around that they are working on making this better. With that said, we need to write code today, right?! Below are a couple of takes on how to do this from others.

Nate Cook was one of the first to really tackle this problem with the solution below. Check out his answer on Stack Overflow with more details.

struct MyOptions : RawOptionSet {
    var value: UInt = 0
    init(_ value: UInt) { self.value = value }
    func toRaw() -> UInt { return self.value }
    func getLogicValue() -> Bool { return self.value != 0 }
    static func fromRaw(raw: UInt) -> MyOptions? { return MyOptions(raw) }
    static func fromMask(raw: UInt) -> MyOptions { return MyOptions(raw) }
 
    static var None: MyOptions          { return MyOptions(0) }
    static var FirstOption: MyOptions   { return MyOptions(1 << 0) }
    static var SecondOption: MyOptions  { return MyOptions(1 << 1) }
    static var ThirdOption: MyOptions   { return MyOptions(1 << 2) }
}
 
func == (lhs: MyOptions, rhs: MyOptions) -> Bool     { return lhs.value == rhs.value }
func | (lhs: MyOptions, rhs: MyOptions) -> MyOptions { return MyOptions(lhs.value | rhs.value) }
func & (lhs: MyOptions, rhs: MyOptions) -> MyOptions { return MyOptions(lhs.value & rhs.value) }
func ^ (lhs: MyOptions, rhs: MyOptions) -> MyOptions { return MyOptions(lhs.value ^ rhs.value) }



Fellow Tutorial Team Member Chris LaPollo came up with the following which is much more succinct, read more on his forum post.

class MyOptions {
  class var None   : UInt32 { return 0 }
  class var All    : UInt32 { return UInt32.max }
  class var First  : UInt32 { return 1 }
  class var Second : UInt32 { return 1<<1 }
  class var Third  : UInt32 { return 1<<2 }
}

Example usage:

physicsBody.categoryBitMask = MyOptions.First
physcisBody.collisionBitMask = MyOptions.First | MyOptions.Second

Dave Lawson has also written an article on the matter that you may be interested in reading.

For now this is where we are left, hopefully in an upcoming beta seed we will see what Apple has landed on!

How does Swift work with Grand Central Dispatch?

The same way, you can use the C APIs as you did in Objective-C.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
    println("test")
});

You can also use the higher level NSOperationQueue as prescribed by Apple when dealing with concurrency.

What about the internationalization macros from Objective-C?

Similar to the NSLocalizedString set of macros from Objective-C you can prepare for internationalization in Swift code by using the NSLocalizedString(key:tableName:bundle:value:comment:) method. The tableName, bundle, and value arguments all have default values. So if you’re used to using NSLocalizedString you can write the following.

NSLocalizedString("Hello", comment: "standard greeting")

Do I need to worry about reference cycles?

Absolutely! It is still possible to create a retain cycle when two objects have a strong reference to each other. To break retain cycles you would use a similar approach that you use in Objective-C. There are three keywords for declaring reference types which are described below; weak and unowned will allow you to resolve reference cycles.

When should I use strong vs. weak vs. unowned references?

  • strong: You should use strong for things you own.

    Strong references cause ARC to retain instances until they are no longer needed. When all strong references are removed the referenced instance is deallocated.

    Note that the strong reference is implied by default, so you do not explicitly declare it.

  • weak: You should use weak for references among objects with independent lifetimes.

    When you set a weak reference to an object, you’re saying that it’s OK with you if the object is deallocated due to memory pressure. Weak values must always be a variable, defined with var and must also be Optional using the ? operator.

    Since weak references are optional, you will never end up with a reference to an invalid instance that no longer exists. ARC will automatically set the reference to nil when the referenced instance is deallocated.

  • unowned: You should use unowned for objects with the same lifetime; such as when an object points back to its owner and you wish to avoid a retain cycle.

    The unowned reference is used whenever a reference will always have a value but when you need to tell ARC to not set the reference to nil.

    unowned behaves similarly to unsafe_unretained in Objective-C. You are responsible for ensuring that you do not access the reference after the referenced object is deallocated, doing so will result in your app crashing. Unowned references must not be optional and cannot be set to nil. Unowned references are also implicitly unwrapped.

Where are the semi-colons?!

Semi-colons are optional in Swift and Apple suggests you stop using them for readability purposes.

However, sometimes semicolons are still used in Swift, such as in for statements:

for var index = 0; index < 3; ++index { ... }

What’s Next?

What is the future of Swift?

This is only version 1, Apple’s intentions are clear that they will be iterating on this language.

So be sure to report bugs and request features! There is a lot of room to see improvements before version 1 is officially released.

How will CocoaPods adapt to swift?

Likely in a similar way. Swift projects still work as Xcode projects and support multiple targets. There is however potential room for improvement with the ability to create modules and custom frameworks.

It is possible that CocoaPods will be reworked to utilize this feature. There are people who have CocoaPods working with Swift projects and the smart people who work on CocoaPods are already discussing this topic.

More Questions?

If you have any questions that were not covered here (I know you do!) please post a comment. I will pick out some of the best ones and update the post with the question and answer – and also give you attribution for asking!

Also, as mentioned earlier, please chime in with any comments or clarifications on the answers listed here and I’ll update as appropriate.

Thanks all, and happy Swift’ing!

Swift Language FAQ is a post from: Ray Wenderlich

The post Swift Language FAQ appeared first on Ray Wenderlich.


Video Tutorial: Saving Data in iOS Part 3: Working with Property Lists

Video Tutorial: Saving Data in iOS Part 4: Encoding and Decoding Objects

Swift Tutorial: A Quick Start

$
0
0
Get started quickly with this Swift tutorial!

Get started quickly with this Swift tutorial!

Swift is Apple’s brand new programming language, just released this year at WWDC.

Along with the language, Swift released an excellent Swift reference guide that I highly recommend.

However, the reference guide is long! So if you don’t have a lot of time and just want to learn Swift quickly, this Swift tutorial is for you.

This Swift tutorial will take around 15 minutes and will give you a quick tour of the Swift language, including variables, control flow, classes, best practices, and more.

You’ll even make a handy tip calculator along the way!

For this Swift tutorial, you will need the latest copy of Xcode (Xcode 6-Beta at the time of writing this Swift tutorial). You do not need any prior Swift or Objective-C experience, but it would help if you had some prior programming experience.

Note: At the time of writing this Swift tutorial, it is unclear to us if we are allowed to post screenshots of Xcode 6 since it is still in beta. Therefore, we are suppressing screenshots in this Swift tutorial until we are sure it is OK.

Introduction to Playgrounds

Start up Xcode 6, and go to File\New\File. Select iOS\Source\Playground, and click Next.

Name the file SwiftTutorial.playground, click Next, and save the file somewhere convenient. Delete everything from your file so you start with a clean slate.

Note: After creating the playground, you may get an error that says “Error running playground: Failed to prepare for communication with playground”. If this happens, simply shut down Xcode and restart it again, and this error should go away.

A playground is a new type of file that allows you to test out Swift code, and see the results of each line in the sidebar. For example, add the following lines to your playground:

let tutorialTeam = 56
let editorialTeam = 23
let totalTeam = tutorialTeam + editorialTeam

As you type these lines, you will see the result of each line on the sidebar. Handy, eh?

Playgrounds are a great way to learn about Swift (like you’re doing in this Swift tutorial), to experiment with new APIs, to prototype code or algorithms, or to visualize your drawing code. In the rest of this Swift tutorial, you will be working in this playground.

Note: At this point, I also recommend you drag your playground file (SwiftTutorial.playground) to your OS X Dock.

This way, you can use this file as a quick scratchpad whenever you want to test out some Swift code.

Variables vs. Constants in Swift

Try adding the following line to the bottom of your playground:

totalTeam += 1

You’ll notice an error when you add this line. This is because totalTeam is a constant, meaning its value can never change. You declare constants with the keyword let.

You want tutorialTeam to be a variable instead — a value that can change — so you need to declare it with a different keyword: var.

Replace the line that initializes totalTeam with the following:

var totalTeam = tutorialTeam + editorialTeam

Now it works! You may think to yourself, “why not just declare everything with var, since it’s less restrictive?”

Well, declaring things with let whenever possible is best practice, because that will allow the compiler to perform optimizations that it wouldn’t be able to do otherwise. So remember: prefer let!

Explicit vs. Inferred Typing

So far, you haven’t explicitly set any types for these constants and variables, because the compiler had enough information to infer it automatically.

For example, because you set tutorialTeam to 56, the compiler knows 56 is an Int, so it set the type of tutorialTeam to an Int for you automatically.

However, you can set the type explicitly if you want. Try this out by replacing the line that sets tutorialTeam to the following:

let tutorialTeam: Int = 56

You may wonder if you should set types explicitly, or let the compiler infer the types for you. We believe it’s better practice to let the compiler infer types automatically where possible, because then you get one of the main advantages of Swift: concise and easy to read code.

Because of this, switch the line back to inferred typing:

let tutorialTeam = 56

Basic Types and Control Flow in Swift

So far, you’ve seen an example of Int, which is the Swift type that is used for integer values, but there’s a bunch more.

Floats and Doubles

let priceInferred = 19.99
let priceExplicit: Double = 19.99

There are two types for decimal point values like this: Float and Double. Double has more precision, and is the default for inferring decimal values. That means priceInferred is a Double too.

Bools

let onSaleInferred = true
let onSaleExplicit: Bool = false

Note that in Swift you use true/false for boolean values (unlike the convention of using YES/NO in Objective-C).

Strings

let nameInferred = "Whoopie Cushion"
let nameExplicit: String = "Whoopie Cushion"

Strings are as you’d expect, except note that you no longer use the @ sign like you do in Objective-C. That might take your muscle memory a bit to get used to! :]

If statements and string interpolation

if onSaleInferred {
  println("\(nameInferred) on sale for \(priceInferred)!")
} else {
  println("\(nameInferred) at regular price: \(priceInferred)!")
}

This is an example of an if statement, just like you’d expect in different languages. The parentheses around the condition are optional, and braces are required even for 1-line statements – w00t!

This also shows an example of a new technique called string interpolation. Whenever you want to substitute something in a string in Swift, simply use this syntax: \(your expression).

At this point, you may wonder where the println output of this code has gone. To see the println output, bring up the Assistant Editor with View\Assistant Editor\Show Assistant Editor.

Here is the playground file up to this point in the tutorial.

Classes and Methods

One of the most common things you’ll be doing in Swift development is creating classes and methods, so let’s jump in right away!

First, delete everything in your playground file so you’re at a clean start.

Next, you’ll create a tip calculator class that will help you figure out what you should tip at a restaurant. You’ll add the code one small piece at a time, with explanations here each step along the way.

// 1
class TipCalculator {
}

To create a class, simply enter the class keyword and the name of your class. You then put two curly braces for the class body.

If you were subclassing another class, you would put a : and then the name of the class you are subclassing. Note that you do not necessarily need to subclass anything (unlike in Objective-C, where you must subclass NSObject or something that derives from NSObject).

Add this code inside the curly braces:

  // 2
  let total: Double
  let taxPct: Double

This is how you create properties on a class – the same way as creating variables or constants. Here you create two constant properties – one for the bill’s total (post-tax), and one for the tax percentage that was applied to the bill.

Note that any properties you declare must be set to an initial value when you declare them, or in your initializer – otherwise you’ll have to declare them as optional (more on that in a future tutorial).

Add this code after the previous block (inside the curly braces):

  // 3
  init(total:Double, taxPct:Double) {
    self.total = total
    self.taxPct = taxPct
  }

This creates an initializer for the class that takes two parameters. Initializers are always named init in Swift – you can have more than one if you want, but they need to take different parameters.

Note that I have given the parameters of this method and the properties of this class the same names. Because of this, I need to distinguish between the two by putting the self prefix before the property names.

If I had given these different names, I wouldn’t I wouldn’t have needed the self keyword, because the compiler can automatically infer that. Pretty cool, huh?

Add this code after the previous block (inside the curly braces):

  // 4
  func calcTipWithTotal(total:Double, taxPct:Double, tipPct:Double) -> Double {
    let tax = total * taxPct
    let subtotal = total - tax
    return subtotal * tipPct
  }

To declare a method, you use the func keyword. You then list the parameters (you must be explicit with the types), add the -> symbol, and finally list the return type.

This is a function that calculates a tip on a bill given the post-tax bill, the tax percentage that was applied to the bill, and the percentage you desire to tip.

Note: According to the Emily Post Etipedia, tips should be pre-tax. That is why this calculator uses the amount before tax before applying the tip!

Add this code after the previous block (inside the curly braces):

  // 5
  func printPossibleTips() {
    println("15%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: 0.15))")
    println("18%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: 0.18))")
    println("20%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: 0.20))")
  }

This is a new method that prints out three possible tips.

Note that when you call a method on an instance of a class, the first parameter does not need to be named, but the rest do. Also note that you don’t need to put self before the property names this time, because the compiler can automatically infer it.

Also, notice how string interpolation isn’t limited to printing out variables. You can have all kinds of complicated method calls and operations right inline if you like!

Add this code to the bottom of the playground (after the curly braces):

// 6
let tipCalc = TipCalculator(total: 33.25, taxPct: 0.06)
tipCalc.printPossibleTips()

Finally, you create an instance of the tip calculator and call the method to print the possible tips.

Here’s what your playground file should look like at this point:

// 1
class TipCalculator {
 
  // 2
  let total:Double
  let taxPct:Double
 
  // 3
  init(total:Double, taxPct:Double) {
    self.total = total
    self.taxPct = taxPct
  }
 
  // 4
  func calcTipWithTotal(total:Double, taxPct:Double, tipPct:Double) -> Double {
    let tax = total * taxPct
    let subtotal = total - tax
    return subtotal * tipPct
  }
 
  // 5
  func printPossibleTips() {
    println("15%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: 0.15))")
    println("18%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: 0.18))")
    println("20%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: 0.20))")
  }
}
 
// 6
let tipCalc = TipCalculator(total: 33.25, taxPct: 0.06)
tipCalc.printPossibleTips()

Check your Assistant Editor for the results.

Arrays and For Loops

Currently there is some duplication in the above code, because you’re calling the calcTipWithTotal method several times with different tip percentages. You could reduce the duplication here by using an array.

Replace the contents of printPossibleTips with the following:

let possibleTipsInferred = [0.15, 0.18, 0.20]
let possibleTipsExplicit:Double[] = [0.15, 0.18, 0.20]

This shows an example of creating an array of doubles, with both inferred and explicit typing.

Then add these lines underneath:

for possibleTip in possibleTipsInferred {
  println("\(possibleTip*100)%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: possibleTip))")
}

Enumerating through items in an array is similar to fast enumeration in Objective-C – note that there are no parentheses needed!

You could also have written this loop like this:

for i in 0..possibleTipsInferred.count {
  let possibleTip = possibleTipsInferred[i]
  println("\(possibleTip*100)%: \(calcTipWithTotal(total, taxPct: taxPct, tipPct: possibleTip))")
}

The .. operator is a non-inclusive range operator and doesn’t include the upper bound value. There’s also a ... operator which is inclusive.

Arrays have a count property for the number of items in the array. You can also look up a particular item in an array with the arrayName[index] syntax, like you see here.

Dictionaries

Let’s make one last change to your tip calculator. Instead of simply printing out the tips, you can return a dictionary with the results instead. This would make it easier to display the results in some sort of user interface for the app.

Delete the printPossibleTips method and replace it with the following:

// 1
func returnPossibleTips() -> Dictionary<Int, Double> {
 
  let possibleTipsInferred = [0.15, 0.18, 0.20]
  let possibleTipsExplicit:Double[] = [0.15, 0.18, 0.20]
 
  // 2
  var retval = Dictionary<Int, Double>()
  for possibleTip in possibleTipsInferred {
    let intPct = Int(possibleTip*100)
    // 3
    retval[intPct] = calcTipWithTotal(total, taxPct: taxPct, tipPct: possibleTip)
  }
  return retval
 
}

Let’s go over this section by section:

  1. Here you mark the method as returning a dictionary, where the key is an Int (the tip percentage as an int, like 15 or 20), and the value is a Double (the calculated tip).
  2. This is how you create an empty dictionary. Note that since you are modifying this dictionary, you need to declare it as a variable (with var) rather than a constant (with let). Otherwise you will get a compile error.
  3. This is how you set an item in a dictionary. As you can see, it’s similar to the literal syntax in Objective-C.

Finally, modify the last line in your playground to call this method:

tipCalc.returnPossibleTips()

Once the playground evaluates, you should see the results as a dictionary in the inspector (click the eyeball for an expanded view).

And that’s it – congratulations, you have a fully functional Tip Calculator in Swift!

Where To Go From Here?

Here is the final playground file with all the Swift code from this tutorial.

Stay tuned for the next part of this series, where you’ll learn how to create a user interface for this app!

In the meantime, if you want to learn more here are some great resources to check out:

I hope that helps, and welcome to the world of Swift! :]

Swift Tutorial: A Quick Start is a post from: Ray Wenderlich

The post Swift Tutorial: A Quick Start appeared first on Ray Wenderlich.

Video Tutorial: Introduction to Swift Part 0: Introduction

Video Tutorial: Introduction to Swift Part 1: Variables and Constants

Swift Tutorial Part 2: A Simple iOS App

$
0
0
Create a simple iOS app in this Swift tutorial!

Create a simple iOS app in this Swift tutorial!

Welcome back to our Swift tutorial series!

In the first Swift tutorial, you learned the basics of the Swift language, and created your very own tip calculator class.

In this second Swift tutorial, you will learn how to make a simple iOS app. Specifically, you will create a user interface for your tip calculator class that you developed last time.

I will be writing this tutorial in a manner so that it is useful for both complete beginners to iOS, and seasoned iOS developers transitioning to Swift.

For this Swift tutorial, you will need the latest copy of Xcode (Xcode 6-Beta at the time of writing this Swift tutorial). You do not need any prior Swift or Objective-C experience, but it would help if you had some prior programming experience.

Note: At the time of writing this Swift tutorial, it is unclear to us if we are allowed to post screenshots of Xcode 6 since it is still in beta. Therefore, we are suppressing screenshots in this Swift tutorial until we are sure it is OK.

Getting Started

Start up Xcode and go to File\New\Project. Select iOS\Application\Single View Application, and click Next.

Enter TipCalculator for the Product Name, set the Language to Swift, and Devices to iPhone. Make sure Use Core Data is not checked, and click Next.

Choose a directory to save your project, and click Create.

Let’s see what Xcode has built for you. In the upper left corner of Xcode, select the iPhone 5 Simulator and click Play to test your app.

You should see a blank white screen appear. Xcode has created a single blank screen in your app; in this tutorial you’ll fill it up!

Creating Your Model

First things first – before you create the user interface for your app, you should create your app’s model. A model is a class (or set of classes) that represents your class’s data, and operations that your app will perform on that data.

In this tutorial, your app’s model will simply be the TipCalculator class you created in the first Swift tutorial, except you will rename it to TipCalculatorModel.

Let’s add this class to your project. To do this, go to File\New\File and select iOS\Source\Swift File. Name the file TipCalculatorModel.swift, and click Create.

Note: You cannot call code from your app that resides in a Playground file. Playground files are just for testing and prototyping code; if you want to use code from a Playground in your app, you have to move it to a Swift file like you’re doing here.

Open TipCalculator.swift, and copy your TipCalculator class from the previous tutorial into the file, and make the following changes:

  1. Rename the class to TipCalculatorModel
  2. Change total and taxPct from constants to variables (because the user will be changing these values as he/she runs the app)
  3. Because of this, you need to change subtotal to a computed property. Replace the subtotal property with the following:
var subtotal: Double {
  get {
    return total / (taxPct + 1)
  }
}

A computed property does not actually store a value. Instead, it is computed each time based on other values. Here, you calculate the subtotal each time it is accessed based on the current values of total and taxPct.

Note: You can also provide a setter for a computed property if you’d like, with syntax like this:
var subtotal: Double {
  get {
    return total / (taxPct + 1)
  }
  set(newSubtotal) { 
     //... 
  }
}

Your setter would update its backing properties (i.e. set total and taxPct based on newSubtotal), but that wouldn’t make sense for this app, so you’re not implementing it here.

  1. Delete the line that sets subtotal in init
  2. Delete any comments that are in the file

When you’re done, the file should look like this:

import Foundation
 
class TipCalculatorModel {
 
  var total: Double
  var taxPct: Double
  var subtotal: Double {
    get {
      return total / (taxPct + 1)
    }
  }
 
  init(total:Double, taxPct:Double) {
    self.total = total
    self.taxPct = taxPct
  }
 
  func calcTipWithTipPct(tipPct:Double) -> Double {
    return subtotal * tipPct
  }
 
  func returnPossibleTips() -> Dictionary<Int, Double> {
 
    let possibleTipsInferred = [0.15, 0.18, 0.20]
    let possibleTipsExplicit:Double[] = [0.15, 0.18, 0.20]
 
    var retval = Dictionary<Int, Double>()
    for possibleTip in possibleTipsInferred {
      let intPct = Int(possibleTip*100)
      retval[intPct] = calcTipWithTipPct(possibleTip)
    }
    return retval
 
  }
 
}

You have your app’s model ready to go – time for the views!

Introduction to Storyboards and Interface Builder

Note: If you are a seasoned iOS developer, this section and the next may be review. To speed things up, you might want to skip forward to the section titled A View Controller Tour. We’ll have a starter project waiting for you there with the user interface for the app pre-created.

You create the user interface for your iOS apps in something called a Storyboard. Xcode comes with a built-in tool called Interface Builder that allows you to edit Storyboards in a nice, visual way.

With Interface Builder, you can lay out all of your buttons, text fields, labels, and other controls in your app (called Views) as simply as dragging and dropping.

Go ahead and click on Main.storyboard in the left side of Xcode to reveal the Storyboard in Interface Builder.

There’s a lot of stuff to cover here, so let’s go over each section of the screen one at a time.

  1. On the far left is your Project Navigator, where your can see the files in your project.
  2. On the left of Interface Builder is your Document Outline, where you can see at a glance the views inside each “screen” of your app (view controllers). Be sure to click the “down” arrows next to each item to fully expand the document outline.


    Right now your app only has one view controller, with only one empty white view. You’ll be adding things into this soon.

  3. There’s an arrow to the left of your view controller. This indicates that this is the initial view controller, or the view controller that is first displayed when the app starts up. You can change this by dragging the arrow to a different view controller, or by clicking the “Is Initial View Controller” property on a different view controller in the Attributes Inspector (more on Inspectors later).
  4. On the bottom of the Interface Builder you’ll see something that says “w Any”, “h Any”. This means that you are editing the layout for your app in a way that should work on any sized user interface. You can do this through the power of something called Auto Layout. By clicking this area, you can switch to editing the layout for devices of specific size classes. You’ll learn about Adaptive UI and Auto Layout in a future tutorial.
  5. On the top of your view controller you’ll see three small icons, which represent the view controller itself and two other items: First Responder, and Exit. If you’ve been developing in Xcode for a while, you’ll notice that these have moved (they used to be below the view controller). You won’t be using these in this tutorial, so don’t worry about them for now.
  6. On the bottom right of Interface Builder are four icons related to Auto Layout. Again, you’ll learn more about these in a future tutorial.
  7. On the upper right of Interface Builder are the Inspectors for whatever you have selected in the Document Outline. If you do not see the inspectors, go to View\Utilities\Show Utilities.


    Note there are several tabs of inspectors. You’ll be using these a lot in this tutorial to configure the views you add to this project.

  8. On the bottom right of Interface Builder are the Libraries. This is a list of different types of views or view controllers you can add to your app. Soon you will be dragging items from your library into your view controller to lay out your app.

Creating your Views

Remember that your TipCalculatorModel class has two inputs: a total, and a tax percentage.

It would be nice if the user could type in the total with a numeric keyboard, so a text field is perfect for that. As for the tax percentage, that usually is restricted to a small range of values, so you’ll use a slider for that instead.

In addition to the text field and slider, you will need a label for each, a navigation bar to show the app’s name, a button to click to perform the tip calculation, and a text field to show the results.

Let’s build this user interface one piece at a time.

  1. Navigation bar. Rather than adding a navigation bar directly, select your view controller and go to Editor\Embed In\Navigation Controller. This will set up a Navigation Bar in your view controller. Double click the Navigation Bar (the one inside your view controller), and set the text to Tip Calculator.
  2. Labels. From the Object Library, drag a Label into your view controller. Double click the label and set its text to Bill Total (Post-Tax):. Select the label, and in the Inspector‘s fifth tab (the Size Inspector), set X=33 and Y=81. Repeat this for another label, but set the text to Tax Percentage (0%):, X=20, and Y=120.
  3. Text Field. From the Object Library, drag a Text Field into your view controller. In the Attributes Inspector, set Keyboard Type=Decimal Pad. In the Size Inspector, set X=192, Y=72, and Width=268.
  4. Slider. From the Object Library, drag a Slider into your view controller. In the Attribute Inspector, set Minimum Value=0, Maximum Value=10, and Current Value=6. In the Size Inspector, set X=190, Y=111, and Width=272.
  5. Button. From the Object Library, drag a Button into your view controller. Double click the Button, and set the text to Calculate. In the Size Inspector, set X=208 and Y=149.
  6. Text View. From the Object Library, drag a Text View into your View Controller. Double click the Text View, and delete the placeholder text. In the Attributes Inspector, make sure Editable and Selectable are not checked. In the Size Inspector, set X=20, Y=187, Width=440, and Height=288.
  7. Tap Gesture Recognizer. From the Object Library, drag a Tap Gesture Recognizer onto your main view. This will be used to tell when the user taps the view to dismiss the keyboard.
  8. Auto Layout. Interface Builder can often do a great job setting up reasonable Auto Layout constraints for you automatically; and it definitely can in this case. To do this, click on the third button in the lower left of the Interface Builder (which looks like a Tie Fighter) and select Add Missing Constraints.

Build and run on your iPhone 5 simulator, and you should see a basic user interface working already!

A View Controller Tour

Note: If you skipped ahead to this section, here is a zip of the project at this point.

So far you’ve created your app’s models and views – it’s time to move on to the view controller.

Open ViewController.swift. This is the Swift code for your single view controller (“screen”) in your app. It is responsible for managing the communication between your views and your model.

You will see that the class has the following code in it already:

// 1
import UIKit
 
// 2
class ViewController: UIViewController {
 
  // 3
  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
  }
 
  // 4
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
 
}

There are some new elements of Swift here that you haven’t learned about yet, so let’s go over them one at a time.

  1. iOS is split up into multiple frameworks, each of which contain different sets of code. Before you can use code from a framework in your app, you have to import it like you see here. UIKit is the framework that contains the base class for view controllers, various controls like buttons and text fields, and much more.
  2. This is the first example you’ve seen of a class that subclasses another class. Here, you are declaring a new class ViewController that subclasses Apple’s UIViewController.
Note: Experienced iOS developers – note that you do not have to put a class prefix on your class names like you did in Objective-C to avoid namespace collisions (i.e. you don’t have to name this RWTViewController). This is because Swift has namespace support, and the classes you create in your project are in their own namespace.

To see what I mean, replace the class declaration with the following:

class UIViewController {
}
 
class ViewController: UIKit.UIViewController {

Here UIKit.UIViewController refers to the UIViewController class in the UIKit namespace. Likewise, TipCalculator.UIViewController would refer to the the UIViewController class in your project.

  1. This method is called with the root view of this view controller is first accessed. Whenever you override a method in Swift, you need to mark it with the override keyword. This is to help you avoid a situation where you override a method by mistake.
  2. This method is called when the device is running low on memory. It’s a good place to clean up any resources you can spare.

Connecting your View Controller to your Views

Now that you have a good understanding of your view controller class, let’s add some properties for its subviews, and hook them up in interface builder.

To do this, add these following properties to your ViewController class (right before viewDidLoad):

@IBOutlet var totalTextField : UITextField
@IBOutlet var taxPctSlider : UISlider
@IBOutlet var taxPctLabel : UILabel
@IBOutlet var resultsTextView : UITextView

Here you are declaring four variables just as you learned in the first Swift tutorial – a UITextField, a UISlider, a UILabel, and a UITextView.

There’s only one difference: you’re prefixing these variables with the @IBOutlet keyword. Interface Builder scans your code looking for any properties in your view controller prefixed with this keyword. It exposes any properties it discovers so you can connect them to views.

Let’s try this. Open Main.storyboard and select your View Controller in the Document Outline. Open the Connections Inspector (6th tab), and you will see all of the properties you created listed in the Outlets section.

You’ll notice a small circle to the right of resultsTexView. Control-drag from that button down to the text view below the Calculate button, and release to connect your Swift property to this view.

Now repeat this for the other three properties, connecting each one to the appropriate UI element.

Note: There’s another, even easier way to connect views to properties on your view controller.

While you have Main.storyboard open, you would open your Assistant Editor (View\Assistant Editor\Show Assistant Editor) and make sure the assistant editor is set to display your view controller’s Swift code.

Then, you would control-drag from your view into the Assistant Editor, right before viewDidLoad. In the popup that appears, you would enter a name for a property to create, and click click Connect.

This would create the property for you in your view controller and connect it in Interface Builder, in a single step. Convenient, eh?

Both ways work; you can choose whichever you prefer for our projects.

Connecting Actions to your View Controller

Just like you connected views to properties on your view controller, you want to connect certain actions from your views (such as a button click) to methods on your view controller.

To do this, open ViewController.swift and add these three new methods anywhere in your class:

@IBAction func calculateTapped(sender : AnyObject) {
}
@IBAction func taxPercentageChanged(sender : AnyObject) {
}
@IBAction func viewTapped(sender : AnyObject) {
}

When you declare callbacks for actions from views, they always need to have this same signature – a function with no return value, that takes a single parameter of type AnyObject as a parameter, which represents a class of any type.

Note: AnyObject is the equivalent of id in Objective-C. To learn more about AnyObject, check out our Swift Language FAQ.

To make Interface Builder notice your new methods, you need to mark these methods with the @IBAction keyword (just as you marked properties with the @IBOutlet keyword).

Next, switch back to Main.storyboard and make sure that your view controller is selected in the Document Outline. Make sure the Connections Inspector is open (6th tab) and you will see your new methods listed in a the Received Actions section.

Find the circle to the right of calculateTapped:, and drag a line from that circle up to the Calculate button.

In the popup that appears, choose Touch Up Inside:

This is effectively saying “when the user releases their finger from the screen when over the button, call my method calculateTapped:“.

Now repeat this for the other two methods:

  • Drag from taxPercentageChanged: to your slider, and connect it to the Value Changed action, which is called every time the user moves the slider.
  • Drag from viewTapped: to the Tap Gesture Recognizer in the document outline. There are no actions to choose from for gesture recognizers; your method will simply be called with the recognizer is triggered.
Note: Just like with properties, there’s a shortcut for connecting actions to methods using Interface Builder as well.

You would simply control-drag from something that has an action (like a button) into the Swift code for your view controller in the Assistant Editor. In the popup that appears, you would select Action and give the name of your method.

This would create a method stub in your Swift file and connect the action to your method in one step. Again, both ways work so it’s just a matter of what is convenient to you!

Connecting Your View Controller to your Model

You’re almost done – all you have to do now is hook your view controller to your model.

Open ViewController.swift and add a property for the model to your class and a method to refresh the UI:

let tipCalc = TipCalculatorModel(total: 33.25, taxPct: 0.06)
 
func refreshUI() {
  // 1
  totalTextField.text = String(tipCalc.total)
  // 2
  taxPctSlider.value = Float(tipCalc.taxPct) * 100.0
  // 3
  taxPctLabel.text = "Tax Percentage (\(Int(taxPctSlider.value))%)"
  // 4
  resultsTextView.text = ""
}

Let’s go over refreshUI one line at a time:

  1. In Swift you must be explicit when converting one type to another. Here you convert tipCalc.total from a Double to a String.
  2. You want the tax percentage to be displayed as an Integer (i.e. 0%-10%) rather than a decimal (like 0.06). So here you multiply the value by 100.


    Note: The cast is necessary because the taxPctSlider.value property is a Float.

  3. Here you use string interpolation to update the label based on the tax percentage.
  4. You clear the results text view until the user taps the calculate button.

Next, add a call to refreshUI at the bottom of viewDidLoad:

refreshUI()

Also implement taxPercentageChanged and viewTapped as follows:

@IBAction func taxPercentageChanged(sender : AnyObject) {
  tipCalc.taxPct = Double(taxPctSlider.value) / 100.0
  refreshUI()
}
@IBAction func viewTapped(sender : AnyObject) {
  totalTextField.resignFirstResponder()
}

taxPercentageChanged simply reverses the “multiply by 100″ behavior, while viewTapped calls resignFirstResponder on the totalTextField when the view is tapped (which has the effect of dismissing the keyboard).

One method left. Implement calculateTapped as follows:

@IBAction func calculateTapped(sender : AnyObject) {
  // 1
  tipCalc.total = Double(totalTextField.text.bridgeToObjectiveC().doubleValue)
  // 2
  let possibleTips = tipCalc.returnPossibleTips()
  var results = ""
  // 3
  for (tipPct, tipValue) in possibleTips {
    // 4
    results += "\(tipPct)%: \(tipValue)\n"
  }
  // 5
  resultsTextView.text = results
}

Let’s go over this line by line:

  1. Here you need to convert a String to a Double. This is a bit of a hack to do this; hopefully there will be an easier way in a future update to Swift.
Note: Here’s how this works, in case you’re wondering.

At the time of writing this tutorial, Swift’s String class does not have access to every method that NSString has (NSString is the string class in the Foundation framework). In particular, Swift’s String class does not have a method to convert to the string to a double; however NSString does.

You can call bridgeToObjectiveC() method on a Swift String to convert it to NSString. Then, you can call any method that is available on NSString, such as a method to convert to a double.

To learn more about the methods available on NSString, check out the NSString Class Reference.

  1. Here you call the returnPossibleTips method on your tipCalc model, which returns a dictionary of possible tip percentages mapped to tip values.
  2. This is how you enumerate through both keys and values of a dictionary at the same time in Swift. Handy, eh?
  3. Here you use string interpolation to build up the string to put in the results text filed. \n is the newline character.
  4. Finally you set the results text to the string you have been building.

And that’s it! Build and run, and enjoy your hand-made tip calculator!

Where To Go From Here?

Here is the final Xcode project with all the code from this Swift tutorial.

Stay tuned for a bunch more Swift tutorials. We’ll be showing you how you can work with table views, Sprite Kit, some iOS 8 APIs, and much more!

In the meantime, if you want to learn more here are some great resources to check out:

Thanks for reading this tutorial, and if you have any comments or questions please join in the forum discussion below!

Swift Tutorial Part 2: A Simple iOS App is a post from: Ray Wenderlich

The post Swift Tutorial Part 2: A Simple iOS App appeared first on Ray Wenderlich.

Video Tutorial: Introduction to Swift Part 2: Strings


Three New Swift Books: Preorders Now Available!

$
0
0
Three Brand New Swift and iOS 8 Books: Preorders Now Available!

Three Brand New Swift and iOS 8 Books: Preorders Now Available!

With the introduction of the Swift language and iOS 8, iOS development is going to change significantly over the coming months and years.

And we’re fully committed to helping you make this transition!

Ever since the WWDC keynote, we’ve been hard at work diving into Swift and getting tons of Swift resources ready for you.

Today, we are very excited to announce three new Swift books are now available for preorder:

  • Swift by Tutorials: Learn Apple’s brand new programming language, Swift, the quick and easy way – via hands-on tutorials!
  • iOS 8 by Tutorials: Learn about the new APIs in iOS 8 such as Adaptive UI, App Extensions, and Cloud Kit. Hit the ground running with all iOS 8 has to offer!
  • Core Data by Tutorials: Core Data is one of the most important APIs to master in iOS – so important it deserves its own book. Fully up-to-date for iOS 8 and Swift, it will show you how to take control of the data in your iOS apps!

Keep reading to find out more about each book.

Swift by Tutorials

Swift by Tutorials

Swift by Tutorials is intended to be a quick and practical introduction to the Swift language for developers who already know the basics of programming.

This book follows the signature ‘By Tutorials’ approach of other books in this series. You will learn by gaining hands-on experience: writing code, and building apps.

This book is packed full of practical advice and real world experience, from the authors of Essential Objective-C and the iOS by Tutorials series.

Topics covered in this book:

  • Variables, constants, and types
  • Strings and collections
  • Classes & structs
  • Control flow
  • Optionals
  • Subscripts
  • Memory Management
  • Swift “Under the Hood”
  • Generics
  • Functions & closures
  • Enums & switch statements
  • Functional programming
  • Swift & Cocoa
  • Swift in Action (making a full iOS App in Swift)
  • …and much more!

You do not need any prior Objective-C or iOS experience for this book, but if you do we’ll make the transition even easier for you by drawing some parallels to what you already know.

Once you’re done reading this book, you’ll be a Swift master and ready to create your own Swift apps!

iOS 8 by Tutorials

Written by: Soheil AzarpourScott BerrevoetsRicardo CepedaTammy CoronSam DaviesMike KatzChris LoweFelipe Laso MarsettiVincent NgoCesare RocchiAudrey TamChris WagnerNick WaynikJack Wu

iOS 8 by Tutorials

Welcome back to the fourth book in our popular iOS by Tutorials series!

In iOS 8 by Tutorials, you will learn about all of the new APIs introduced in iOS 8, from Adaptive UI to App Extensions to Cloud Kit via hands-on tutorials.

This book is for intermediate to advanced iOS developers who already know the basics of iOS development. All examples in this book will be in Swift, so you should read Swift by Tutorials first (or have equivalent knowledge).

Topics covered in this book:

  • Adaptive UI: Learn how to make your apps adapt to different screen sizes with Unified Storyboards, Size Classes, Traits, and more.
  • Presentation Controllers, Transition Coordinators, and UISplitViewController Changes: Learn how to present and animate your view controllers on multiple devices, using the same code.
  • App Extensions: Learn how to make extensions of all types: from Today to Share to Action to Photo Editing and more.
  • Cloud Kit: Learn how to store your app’s data between multiple users with the new and powerful Cloud Kit framework.
  • Xcode 6 in Depth: Learn about new features in Xcode 6 like Playgrounds, View Debugging, and more.
  • TestFlight Integration: Learn how to beta test your app using the brand new TestFlight integration in Xcode.
  • Localization: Learn about the new localization workflow in Xcode 6.
  • Custom Controls in Interface Builder: Learn how to expose and configure your custom controls in Interface Builder.
  • Handoff: Learn how to pass the user’s current work between devices.
  • Touch ID Authentication: Learn how to authenticate your user via Touch ID in your apps.
  • Scene Kit: Learn the basics of using Scene Kit from an app developer’s perspective.
  • Visual Effect (Blur) View and Vibrant Text: Learn how to easily add blur effects and vibrant text into your apps.
  • And much more…: From UIKit improvements to photo improvements to the Modern WebKit framework, there are many more goodies in store for you!

iOS 8 by Tutorials is the quickest and easiest way to upgrade your iOS development skills to iOS 8. We can’t wait to take a tour of iOS 8 with you!

Core Data by Tutorials

Written by: Saul MoraSaul MoraPietro ReaPietro Rea

Core Data by Tutorials

Core Data is one of the most important APIs to master in iOS development – but also has one of the largest learning curves!

Don’t worry, we’ve got you covered. This book will take you all the way from beginning concepts all the way to advanced real-world issues, guiding you every step along the way.

This book is packed full of practical advice and real world experience, from the developers of MagicalRecord, NSBrief, and the iOS by Tutorials series.

And best of all – this book is fully up-to-date for iOS 8 and Swift!

This book is for intermediate to advanced iOS developers who already know the basics of iOS development. All examples in this book will be in Swift, so you should read Swift by Tutorials first (or have equivalent knowledge).

Topics covered in this book:

  • The Core Data Stack: Learn about all of the components of the Core Data stack: NSManagedObjectModel, NSPersistentStoreCoordinator, and NSManagedObjectContext.
  • The Core Data Model Editor: Learn how to create Core Data models using the editor, including types, relationships, fetched properties, and data validation.
  • Fetching, Updating, Saving, and Deleting: Learn how to fetch, update, save, and delete data using NSFetchRequest, NSSortDescriptor, faulting, and uniquing.
  • NSFetchedResultsController: Learn how to use NSFetchedResultsController to easily display your data in table views, collection views, and more.
  • Multithreading: Learn how to use Core Data in a multithreaded app, including using parent-child NSManagedObjects and using different Core Data concurrency types.
  • Synchronizing with a web services: Learn how to use Core Data to synchronize with a web service, using Parse and AFNetworking.
  • Core Data and iCloud: Learn how to store your app’s data in the cloud with Core Data and iCloud integration.
  • MagicalRecord: Learn how to use MagicalRecord to simplify your Core Data code.
  • Versioning & Migration: Learn how to upgrade and change your Core Data model over time with lightweight and heavyweight migrations.
  • Persistent Store Configurations: Learn how to create multiple persistent stores, including creating your own NSIncrementalStore.
  • Core Data Performance: Learn how to improve the performance of your Core Data apps and manage the tradeoffs of speed versus memory consumption.
  • Core Data and Unit Tests: Learn how to effectively test your Core Data apps with XCUnit.

This book is the best way to take your Core Data knowledge from beginning to advanced, fully up-to-date with the latest version of iOS, Xcode, and Swift.

What About Games?

As we mentioned earlier, iOS Games by Tutorials will be updated for Swift as a free update for existing customers.

But we have some more surprises in tune for game developers beyond that – stay tuned for a future announcement! :]

Preorders Available!

Three Brand New Swift and iOS 8 Books: Preorders Now Available!

Three Brand New Swift and iOS 8 Books: Preorders Now Available!

We’re very happy to announce that you can preorder these new Swift Books today!

You can either preorder the books individually from the raywenderlich.com store, or you can save over $10 by buying the bundle of the three new Swift books.

We hope to release the books soon after iOS 8 is released. By preordering the books, you will receive the books the minute they become available, and become one of the first to use these techniques (and our sample project code) in your own apps.

We hope you are as excited about these Swift books as we are – we really think you are going to love these, we’re putting a lot of heart and soul into them.

Get these books as soon as possible – preorder now!

Three New Swift Books: Preorders Now Available! is a post from: Ray Wenderlich

The post Three New Swift Books: Preorders Now Available! appeared first on Ray Wenderlich.

Tools for Running an iOS Consulting Studio

$
0
0
Get your organization on track with these tips and tools.

Get your organization on track with these tips and tools.

Management responsibilities are a sharp departure from the technical skills that make developers successful in the first place. However, growing into a larger organization doesn’t need to be overwhelming. Everything you need to organize and maintain a successful team is just a few mouse clicks away.

I’ve gathered a great list of tools and services that I’ve found essential while running Mac and iOS development companies for over a decade. Hopefully you’ll find one or more things in this list to help solve your own organization’s growing pains!

Full disclosure: My employer (MartianCraft) has an interest in Briefs, Resolve, Propane, and Slender. We often create tools that fill a need we have in day to day operations.

Design and Polish

To put it simply, design is critical. If you aren’t making beautiful software you won’t captivate your users, clients, coworkers or peers.

When you’re a one-person shop, it’s easy to manage the design phase by yourself. However, when you need to collaborate and share ideas with two, five, or dozens of stakeholders, the process becomes a tad more complicated.

Here are my picks for some of the best communication tools for your organization:

InVision

InVision is a free web app where you can post, solicit feedback on, and track changes to your designs.

Real-time sharing and presentation

Real-time sharing and presentation

In essence, it’s a bug tracker that supports images and other mockups in various file formats. Invision provides the ability to create a clickable map from your art assets that you can use to demo the flow through your app.

Clients will find the InVision site easy to use without much hand-holding, and they’ll undoubtedly appreciate the opportunity to be involved in the early stages of the design process.

LayerVault

LayerVault provides version control for your PSDs and other popular design formats. You can store an unlimited number of revisions online and sync them directly to your computer á la Dropbox to give you the seamless workflow you need.

Smart versioning for design files

Smart versioning for design files

LayerVault includes support for resolvable conversations tagged to a change as well as release notes on new updates. If you have more than one designer editing a PSD (and you know all too well the issues that can cause!), then LayerVault will be an invaluable tool in your arsenal.

Briefs

With Briefs you can professional quality prototypes from mockups and wireframes, share them with your team and easily deploy them to iOS and Android devices as in-hand demos.

kr-briefs

Briefs is great for rapid prototyping, and clients get the chance to to experience the interaction and flow of the app — even before development kicks off.

OmniGraffle

OmniGraffle is one of the best tools out there for quickly assembling wireframes. There are templates for iOS apps and icons, and you can add your own stencils to customize your designs.

Stencils Customisation

I know that there are a lot of other less-expensive and free solutions for wireframing, but OmniGraffle keeps returning to my workflow. As a general-purpose diagramming tool, OmniGraffle is also great for sketches, flow charts and illustrations. The free OmniPresence sync solution can also help you keep track of OmniGraffle documents across devices (Mac and iPad) and teammates.

Slender

Slender analyzes the image usage of iOS and Mac apps. Not only can it reduce the size of a finished app, but it can also point out other image and code issues that might result in blurry or incorrect user interfaces.

Slender

Slender’s value becomes apparent each time Apple introduces new resolutions and screen sizes to iOS devices.

xScope

If you need to quickly measure, compare, align, and inspect design elements in your apps, xScope is your tool.

xScope

It’s a breeze to compare your final product to the original design mockups, helping you make sure that your clients and end-users get exactly what they were promised.

Reveal App

Debugging and troubleshooting layout issues in your iOS apps can be a real pain. Reveal produces three-dimensional representations of every layer in your interface for you to inspect.

Reveal app

SparkInspector remains a slightly cheaper, but comparable, solution.

Communication

Old phone

Keep your communications technology up to date with your developer technology. Photo credit: hux

It’s become difficult to find talented people in local markets and the pool of available talent is shrinking every day. The solution? Create a virtualized company out of remote employees.

Remote companies are increasingly common in today’s business environment, and especially so in the mobile consulting world. Effective communication is what makes or breaks a company — doubly so for a remote company. You need to manage all aspects of communication in your organization with your employees, teams, managers, clients and especially your users.

Without established communications, your company won’t even have a chance to get off the ground. Fortunately, I’ve done a bit of digging for you and have found the tools below to be of great value to stay connected with everyone in your organization.

Adium

Every company needs a one-to-one communication tool to encourage dialogue outside of email. You can use Skype, AIM, Gtalk, Yahoo Messenger, Jabber or any of the other great chat platforms out there to let people communicate in real time.

Adium, an open source chat client, takes care of the headaches of cross-platform chat and works with most major chat platforms, with the exception of Skype. Say your team is standardized on AIM but your client prefers Gtalk – Adium supports both and lets you keep your communication in one app.

Facetime

A lot of things can get lost in “electronic translation”: emails, chats, and even phone calls don’t always convey the true intent of a message. If your company is working remotely, consider using video conferencing systems such as Facetime on a regular basis.

For large groups of people, GotoMeeting and Google Hangouts are useful tools for communicating via voice and video.

Campfire

Direct communication using chat platforms and Facetime is great, but it doesn’t simulate the typical office dynamic for distributed teams. 37Signals provides Campfire as a solution to that issue, providing a “lobby” and “room” metaphor to your chat rooms. You can chat, share files, and there’s even a conference call dial-in option.

Propane is a companion app to Campfire that provides an desktop native solution over the default website. Flint also provides Mac and iOS clients for Campfire.

Reflector

Have you ever tried to gather a group of people around your iPhone in a boardroom to demo a feature or a new app? It’s pretty much impossible, and it looks terribly unprofessional. Sometimes the iOS Simulator just doesn’t cut it either. Enter Reflector, which lets you mirror the screen of your device back to a Mac in order to showcase your demo or even record the screen. Problem solved! :]

Project Management

Instat messages, video chat and remote demos are great “live” tools, but you’ll also need some way communicate asynchronously. In addition to the old standby of email, project management tools let you archive and track comments, issues, tasks, etc.

Here are some more communication tools targeted to project management.

Basecamp

When designing and building any project, it’s essential to have a single place to track changes, feedback, and notes associated with your project. Basecamp offers these services in a package that’s not only useful, but client-friendly as well.

One caution I would offer about Basecamp is as projects grow beyond a certain size, project details can easily become lost in the cracks; sometimes, managing large-scale projects on Basecamp can become a full time job in and of itself.

Lighthouse App

As a solo developer, it’s easy to keep a whiteboard or a paper journal of outstanding bugs and yet-to-be-implemented features. However, this approach doesn’t scale very well when you work in teams. Lighthouse tracks project issues with very little extraneous noise and has just enough features to replace the whiteboard without being overly complicated.

If you’re looking for an iOS companion to Lighthouse App check out Resolve, which lets you manage tickets and receive push notifications right on your device.

GitHub Issues

Much like Lighthouse, GitHub Issues is a lightweight ticket tracking system built on top of Github. This makes it an ideal choice for companies who host code in GitHub. Choosing between Github and Lighthouse mostly comes down to personal preference.

There are a number of more complex bug tracking platforms available, such as Jira and Fogbugz. These platforms have many more features than Github Issues and Lighthouse — but those features come at a cost of extra complexity.

When choosing a ticketing system for your development shop, spend some time upfront and consider which platform best fits your team’s workflow, since switching tracking platforms down the road can be quite a lot of work.

Invoicing, Payroll & Accounting

Tracking cash flow is a crucial aspect of any business. Unfortunately, a lot of organizations overlook this and discover this fact after they encounter serious problems with their finances, at which point it is usually too late to recover gracefully. I’ve seen many companies fold because they thought they had more money than they actually did.

Keeping a careful eye on the financials of a company can alert you to potential problems months, or even years, before they have an impact on your business. Careful recordkeeping keeps you aware of the financial direction of the company and gives you a lot of data on which to base your business decisions.

To that end, here’s some of the accounting software that makes working with that dirty aspect of the business — money — just a little more bearable.

FreshBooks

FreshBooks is an online invoice and time tracking system. A basic FreshBooks account is free and it’s quite affordable to upgrade to more feature-rich accounts as your business dictates. FreshBooks can track your employees’ time, process invoicing for clients and track expenses and reciepts.

More advanced features let clients pay their invoices via credit cards or PayPal. If your organization requires a high level of integration with FreshBooks, you can take advantage of the powerful API to integrate FreshBooks into your existing or future internal systems. With highly customizable reports and both iOS and Android apps available, you’ll be able to keep tabs on your business accounting.

QuickBooks Online

Historically, QuickBooks on the Mac has been a second fiddle to its Windows cousin. However, QuickBooks Online is a full-featured Mac compatible alternative and lets you easily share information with business partners, accountants, advisors, and investors.

FreshBooks helps you keep track of employee cost and incoming client revenue, but QuickBooks can keep an eye on other expenses and costs associated with your business. When tax time rolls around, having solid records can save you a lot of money, not only in proper tax deductions but also expensive hourly accountant fees!

Client Relationship Management

Most freelancers who have been around for a while have at least one story of losing clients simply because they forgot to follow up on client leads! It’s incredibly easy to let potential leads slip through your fingers while you’re occupied with managing existing clients, products, employees, payroll and all the other minutiae associated with running a business.

Even though you might be crazy busy with your business now, you could certainly face a period of famine at some point down the road when work dries up. Without the momentum created today from following up with clients, it’s a lot harder to build a sales pipeline when the lean times are upon you.

Payroll and other monthly obligations can make it extremely hard to recover from a lack of active client work. A Customer Relationship Manager (CRM) tool will help you build and maintain your sales pipeline to avoid critical business errors like ths.

There are lot of CRM options out there, but a lot of them deal with selling products to customers and aren’t ideal for a service-based model like software development. Through trial and error — and a lot of mistakes! — I’ve narrowed down the list to three solutions that work best for mobile consulting shops.

Highrise

This CRM offering from 37Signals is a good choice for lead tracking. While Highrise lacks a number of advanced features such as percentage chance of closing, charting patterns, and forecasting, it does a good job with basic features like creating deals, tracking email correspondence and built-in shared to-do lists.

Insightly

Insightly’s biggest selling feature is its integration with Google Apps. If you’re using Google Apps for email and other business services, Insightly might be the right choice for you. The downside is you need to use Google’s web portal to access the built-in features of Insightly. The feature set is a little richer than Highrise, but its interface can be more difficult to navigate.

Salesforce

Salesforce is the leader of CRM systems; it’s a beast of a software package that does it all. The downside of Salesforce is it undoubtedly contains a large number of features you have absolutely no interest in using — and the price tag reflects this. However, if your organization is large or is planning to scale quickly, then Salesforce might be the solution to your growing organization’s CRM needs.

Source Control and Versioning

If you’re into the code game, then you need to have some sort of version control system in your shop. Without it, you’re running the risk of losing or corrupting all of your most important assets — your code and other associated elements that make up your products or services. Organizations that lose their core assets don’t tend to stick around for very long! :]

There are a lot of tools to version and manage your code, but here are a few of the best:

GitHub

Shared source control is important for everyone from solo developers, but a good version control system is an absolute necessity when working with larger groups like contractors, employees, or even clients.

GitHub makes it easy; from pull requests and code review to complex team management, GitHub does almost everything you’d expect in a good source control system.

GitHub pull requests

Changes

Git, for all of its great features, lacks a really great tool for performing file diffs. Many organizations have attempted to build the ultimate diff tool, but several ones worth a mention are Black Pixel’s Kaleidoscope and Apple’s Diff Engine in Xcode.

At the end of the day, I keep returning to Changes as it has a great minimalistic interface and gives me the direct interaction with my code that I’m looking for.

Changes

SourceTree

Although I’m a big supporter of command-line Git interaction, many developers prefer a visual app to manage their source control activities. SourceTree is a feature rich Git Mac app that makes branching, cloning, creating submodules and everything else in the Git toolkit simple and easy.

SourceTree

Hosting

I started my first consulting company with $5 to host a website. An iOS development shop doesn’t really need more than a simple website and email address to be in business. However, keep in mind that your website reflects the professionalism of your organization, and the days of clients flying in to visit your offices before choosing you for a project are quickly fading.

Building a solid, fast, and beautiful website is an absolute must for mobile consulting shops. Although not all of us are born web designers, the following services will provide a solid back end to your website or online service.

A Small Orange

A Small Orange is my go-to hosting provider; while I’ve had a number of problems with their customer support, in the end they have always been able to resolve my issues. Their service has fantastic uptime and bandwidth and has handled traffic spikes even during the most demanding product launches. Their plans are surprisingly affordable for the amount of computing power they offer.

Digital Ocean

When hosting APIs and other backend services, Digital Ocean is my provider of choice. Their super fast SSD backed servers start at very low prices and have a lot of scalability options. They’ve recently edged out the legendary RackSpace in terms of offerings.

Heroku

Heroku is a fantastic hosting provider during project staging and development. Their free plans are a great way to start developing quickly, pushing off worrying about payment until later in the process. While Heroku can scale to accommodate production environments, the cost of their service scales accordingly.

Parse

Parse is an easy and affordable way to build out server APIs for simple iOS apps; this ease of use is great for clients or teams that aren’t experienced with PHP or Ruby on Rails. Parse also offers analytics and push notification frameworks for more advanced business requirements.

Even though it’s easy to use, Parse has its limitations. As your app’s requirements grow and mature, it can be fairly easy to work yourself into a corner where Parse is no longer be a viable solution. This frequently requires a completely new server build-out, or worse, a sacrifice of your apps features.

Check out our tutorial on Parse to get started: How To Easily Create A Web Backend for Your Apps with Parse

HockeyApp

While TestFlight remains a large and popular player in the field of over-the-air app distribution, HockeyApp is my preferred supplier for its uptime and ease of use. If you’re still manually emailing IPAs back and forth to clients, HockeyApp is worth looking into. As a bonus, HockeyApp has features beyond distribution and hosting, including crash collection and analysis tools.

Where To Go From Here?

The tools from this article are supplementary and should solve a particular problem or save you some time. Business owners often find themselves neck-deep in third-party solutions that promise to make their lives easier, but in the end just complicate matters further. Remember to keep things simple – the most important tools to ensure your success are the ones that brought you to this point!

To be successful in business, study those developers and companies you admire and read as much as possible about the mistakes others have made and the lessons learned as a result.

Check out some some lists and reviews for tools to help you on your way if you want more reading (or podcast listening!) to do:

If you have a tool or service that your shop just can’t live without, come share it with us in the discussion below!

Tools for Running an iOS Consulting Studio is a post from: Ray Wenderlich

The post Tools for Running an iOS Consulting Studio appeared first on Ray Wenderlich.

WWDC Reflections: The raywenderlich.com Podcast Episode 7

$
0
0
Episode 7: WWDC Reflections

Episode 7: WWDC Reflections

In this episode, we have a deep discussion on all of the news from WWDC, now that we’ve had a little bit of time to play around with some of the new goodies!

[Subscribe in iTunes] [RSS Feed]

Here’s what is covered in this episode:

  • What’s new in raywenderlich.com: Best new tutorials and sneak peek of coming month
  • News/Tech Talk: WWDC Reflections

Links and References

Our Sponsor

  • AppCode: An intelligent Objective-C IDE that helps iOS/OS X developers create outstanding apps with ease and pleasure.

What’s New on raywenderlich.com

News/Tech Talk: WWDC Reflections

Contact Us

Where To Go From Here?

We hope you enjoyed this podcast! We have an episode each month, so be sure to subscribe in iTunes to get access as soon as it comes out.

We’d love to hear what you think about the podcast, and any suggestions on what you’d like to hear in future episodes. Feel free to drop a comment here, or email us anytime at podcast@raywenderlich.com!

WWDC Reflections: The raywenderlich.com Podcast Episode 7 is a post from: Ray Wenderlich

The post WWDC Reflections: The raywenderlich.com Podcast Episode 7 appeared first on Ray Wenderlich.

Call for Applicants: raywenderlich.com Update Team

$
0
0
Join the raywenderlich.com Update Team and level up your skills!

Join the raywenderlich.com Update Team and level up your skills!

This site is a joint effort by a team of over a hundred developers and authors from across the world. We have an editing team, a tutorial team, a forum subject matter expert team, and more.

Well, today I’m very happy to announce that we’re starting a brand new team at raywenderlich.com: the Update Team!

We are starting a massive new project called the “Great Blog Update” to modernize our most popular tutorials to the latest iOS 8 APIs, and more importantly – to update them to Swift! :]

This is where you come in! We are currently looking for applicants to join this brand new team. Keep reading to find out why you might want to join, and what’s involved!

Why Apply?

There are many great reasons to join the raywenderlich.com Update Team:

  • It’s a learning experience. By following along with a tutorial and updating it, you’ll be learning the concepts as you go. It’s also a great way to get up to speed on Swift while getting paid!
  • Great foot in the door. We don’t recruit that often for the team; we only have call for applicants like this a couple times a year. This is a great way to get your foot in the door; if you do a good job it will be easy to transition to a tutorial team, editing team, or other position.
  • Become part of the community. You’ll be joining our community of writers and editors. Team members get access to opportunities not available to anyone else, such as joining our private IRC channel, contributing to our books and products, writing starter kits, working on team projects, and much more.
  • Personal Exposure. This site gets a lot of traffic which means your updates will be read, commented on, tweeted out, and generate feedback. You can be sure that a lot of people will notice and enjoy your hard work!
  • Ease into writing. The Update Team is a great way to be part of the site without the more substantial commitment of joining the Tutorial Team. Updating an existing tutorial is easier than coming up with a new one from scratch, and is a much lighter time commitment too.
  • Money! The first tutorial you update is not paid, but after that you will be paid for each update. You can expect to update at least one tutorial every two months – more if your schedule permits!
  • Free Stuff! And as a final bonus, by joining the Update Team you will get a lot of free stuff! You’ll get a free copy of all of the products we sell on the site – over $500 in value total!

This is an informal, part-time position – you’d be updating about 1-2 tutorials per month. We do expect that when you are assigned a tutorial, that you complete the update within 1 week.

How to Apply

We’re looking for experienced iOS developers with good writing skills. You should be a quick learner, able to read code, and have some Swift experience already.

If you meet the above requirements and want to apply to join the team, please send me a direct email with the following information:

  • Introduce yourself and describe your iOS experience.
  • What is the best app you’ve made or worked on, and why are you proud of the work you did on this app? (Please include an App Store link)
  • What is your favorite Swift language feature?
  • Why are you interested in joining the raywenderlich.com Update Team?

For the applicants that look most promising, we will send you an invite to an official tryout process where you will perform a short mock tutorial update. Those that pass the tryout will become full members of the team!

Note: We usually get many emails when we do a public call for applicants, so please understand we may not have time to respond to everyone. We do promise to read each and every email though!

Thanks for considering applying to join the raywenderlich.com Update Team, and we are looking forward to working with you! :]

Call for Applicants: raywenderlich.com Update Team is a post from: Ray Wenderlich

The post Call for Applicants: raywenderlich.com Update Team appeared first on Ray Wenderlich.

Video Tutorial: Introduction to Swift Part 3: Arrays

Viewing all 4373 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>