-
Have you ever thought about how awesome it would be to make your own apps for your iPhone or iPad?
There’s never been a better time to learn than now – especially since Apple just released a brand new programming language: Swift!
This is a tutorial series for complete beginners to iOS development, that will take you from the basics (like beginning Swift programming topics, or making a command-line app) all the way to making a full iOS app with a beautiful user interface.
With iOS app development, the sky is the limit. This Swift tutorial series will provide you with the basic knowledge you’ll need to make the amazing apps you’ve dreamed of!
Note: If you are a complete beginner to programming, this tutorial is for you! If you already have some experience with programming and want something faster paced, check out this tutorial series.Getting Started
The very first step is to download Xcode – the software program that you write your apps in. You can download it for free on the Mac App Store:
Be sure you have the latest version of Xcode – you need Xcode 6 or later to work with Swift.
Once you have Xcode installed, open Xcode and click the button that says Get started with a playground.
Note: If you don’t see the “Welcome to Xcode” window, click WindowWelcome to Xcode to display it.A playground is a simple way to experiment and play around with Swift code.
You cannot run a playground as an iPhone app, but it will be very important in helping you to understand the basics of Swift. Don’t worry, you’ll be creating your very own iPhone app soon enough!
Set the name to MyPlayground, the platform to iOS, and click Next. Save the playground wherever you wish.
Introduction to Playgrounds
You will see that the playground you created already has three lines of code:
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground"
Let’s go through each line, one at a time.
// Playground - noun: a place where people can play
This first line, which starts with two forward slashes, is called a comment.
This line is only there for you, or any other programmers that look at your code, to see. It does not affect the way that your code functions. Think of it as “a way to write notes in your code”.
import UIKit
The second line imports UIKit, which you can think of as “a bunch of code written by the smart folks at Apple.” All you need to know about this right now is that you need it for the rest of your code to work.
var str = "Hello, playground"
The third line is the one you should focus on right now.
This line creates a variable named str that holds the value
Hello, playground. On the right side of the window, you can see that Xcode is keeping track of what value this variable holds.Try changing
"Hello, playground"to"Look what I can do!", like this:var str = "Look what I can do!"
Did you see how the right side of the window changed what it said too? Congratulations, you just did some programming!
Your Own Calculator
Now let’s see what else you can do. At the bottom of your file, try typing a basic math expression such as
2 + 2and hit enter to go to the next line:2+2
The playground will give you the answer to your equation over in the shaded right side of the window:
Cool, eh? You can do any other math operation too.
Challenge: Quick – try to use Playgrounds to tell me the result of 123 * 456!
Solution Inside: Solution Show Using playground as a simple calculator is great and all, but now let’s move on and get into some more coding! Delete everything in the program except for
import UIKitso you have a clean slate to work with.import UIKit
It is extremely important that you leave that line there because the Playground will not work without it.
Variables
Next, lets play some more with some variables.
You use variables to store values. When you create a variable, you always use the following syntax:
var yourVariableName: yourType = yourInitialValue
Except you substitute the following:
yourVariableName: Whatever you want to name the variable, likestroragefor exampleyourType: The type of the variable, likeStringorInt. More on that in a moment.yourInitialValue: Whatever you want to set the initial value of the variable to, like “Look what I can do!” or 18.
Let’s try an example! Add these lines to the bottom of your playground:
var str: String = "Look what I can do!" var age: Int = 18
In the first line, you created a variable named
strof typeString, and set the initial value to “Look what I can do!”In the second line, you created a variable named
ageof typeInt, and set the initial value to 18.You’re starting to get a good idea how how to make a variable, but you may be wondering what the difference between
StringandInttypes is, and what other types you can use. Let’s discuss that next!Types
Here is a list of some of the basic data types that Swift has to offer:
- Int – whole numbers, or integers
- Double – decimal numbers
- Bool – a value that can be true, or false
- String – a “string” of letters or words
Let’s practice using these data types. Add the following lines to the bottom of your playground:
var luckyNumber: Int = 7 var costOfCandy: Double = 1.25 var hungry: Bool = true var name: String = "Ryland"
Notice how each of the values show up on the shaded right area of the window as the playground keeps track of them. Now, try changing the value of the String name.
Add the following line to the bottom of your playground:
name = "Ry"
This line did not require the use of
varor: Stringbecause the object was already created. All you did here was change the value that it was storing.Challenge: Your turn to give it a try. At the bottom of the file, try creating a variable to represent your favorite video game.
Solution Inside: Solution Show Constants
There are also special types of variables called constants.
Rather than declaring them with
var, you use the keywordlet. What this does, is it makes the immutable, or unchangeable.Whenever possible, you should use
letrather thanvarbecause it allows your code to run faster because the compiler doesn’t have to account for the possibility that the value may be changed. Any data type can be used as a constant, just as any data type can be used as a variable.Let’s try creating some now. Add this code at the bottom of your playground file:
let life: Int = 42 let pi: Double = 3.14 let canTouchThis: Bool = false let captain: String = "Kirk"
Now try assigning a new value to
captain, such as"Hook". Type this line of code at the bottom of your playground file:captain = "Hook"
Notice that a small red symbol with an exclamation mark comes up on the far left-hand side. This is telling you that an error has occurred in your code.
Click on the symbol, and see that the error message Cannot assign to ‘let’ value ‘captain’ pops up. This is telling you that since you initialized the variable with
let, therefore making it a constant, its value cannot be changed.Remove the line
captain = "Hook"to get rid of the error.Challenge: Make a constant named
favoriteNumberof typeInt, and set the value to your favorite number.Solution Inside: Solution Show Inferred Typing
Tired of typing yet? No need to fear, Swift is smarter than you might think.
There is a new feature in Swift called Inferred Typing. This means that if you provide enough information when declaring and initializing the variable, Swift can predict the data type so you don’t have to include it every time.
Not only does this save time and energy from typing, but it also makes your program less cluttered and easier to follow.
To try this, find your line that says
var luckyNumber: Int = 7and replace it with the following:var luckyNumber = 7
This may not seem like that big of a deal right now, but it will save you a lot of typing in the long run!
Just remember, inferred typing only works if you provide the right amount of information. If you wanted
luckyNumberto be aDouble, you would have had to set it equal to7.0(to make it clear that it’s a decimal number, rather than7which is an integer).Challenge: Go back and try to make sure all of your variables and constants use inferred typing.
Solution Inside: Solution Show Comparison Operators
Just like Playground can do simple math operations as explained earlier, it can compare numbers and values. Some of these operators include:
- > Greater Than
- < Less Than
- == Equal To
- >= Greater Than or Equal To
- && AND
- || OR
You can use these operators to compare two values.
Let’s give this a try! First, add these lines to the bottom of your playground to declare some variables and initiate them with values:
let batmanCoolness = 10 var supermanCoolness = 9 var aquamanCoolness = 1
Great! Now you can use these two variables to test our comparison operators. Place the following block of code at the end of your Playground file.
batmanCoolness < aquamanCoolness supermanCoolness >= 8 batmanCoolness == (aquamanCoolness + supermanCoolness) batmanCoolness > aquamanCoolness && batmanCoolness == (aquamanCoolness + supermanCoolness) batmanCoolness < supermanCoolness || aquamanCoolness < supermanCoolness
Review the results in the shaded right-hand side of the window. Playground will evaluate your statements and tell you if they are true or false.
For the AND statements (
&&), both comparisons have to be true. For the OR statements (||), only one of the two comparisons has to be true. If the first one is true, the program doesn’t even bother to evaluate the second because there is no need to.Challenge: Try adding a new variable for Spiderman called
spidermanCoolnessand give him a coolness value. Then try using some of the comparison operators (like >, <, ==, &&, and ||) to compare Spiderman’s coolness to other superheroes. (Notice that I made batmanCoolness a constant so you can’t change it)
Solution Inside: Solution Show If/else statements
In if/else statements, the computer executes a certain block of code if a condition is true, and does not execute the code if the condition is false.
Let’s try this! Add this example to the bottom of your playground:
if (batmanCoolness > spidermanCoolness) { spidermanCoolness = spidermanCoolness - 1 } else if (batmanCoolness >= spidermanCoolness) { spidermanCoolness = spidermanCoolness - 1 } else { spidermanCoolness = spidermanCoolness + 1 }This block of code decreases Spiderman’s coolness if Batman is cooler, but increases Spiderman’s coolness if Spiderman is cooler.
As you can tell from the Playground, Spiderman’s coolness decreases to 6 from the realization that he is not as cool as Batman. As you can see from the grey area, the program never goes through the
else ifstatement, even though it is true. That is because the program has already found that the firstifstatement was true, so it doesn’t even look at the rest of the code in the if/else statements.Challenge: Create your own control flow statements using the superheroes from the last example. Remember, none of the
iforelse ifstatements have to be true. The program will either perform theelsestatement if you have one, or just move on to what is next in the program.Solution Inside: Solution Show Simple Functions
Functions are blocks of code that perform a certain task. For example, a function named
printMyFavoriteSnack()might print out"Pringles".You can either write and use your own functions, or use functions written by other programmers. For example, Apple has provided a bunch of built-in functions that do useful things that you can use in your apps.
One example is the
println()function. When you callprintln, the program “prints” whatever you type inside the parentheses to the console.Let’s try a quick example. Type the following at the bottom of your file:
println("Hello, World")You should see “Hello, World” printed out on the right hand side.
Programming anything involves using a lot of different functions. Sometimes you use functions written by Apple or by other people, as you have just done, and sometimes you write your own, as you will experience further along.
Challenge: Try changing the string inside the
println()function to say something nice about yourself. Also, try putting one of the superhero coolness factor variables in there and see what happens.Solution Inside: Solution Show String Interpolation
Printing strings to the console is great and all, but wouldn’t it be great if you could combine a string and the value from a variable in the same print statement?
Good news, everyone! You can! It’s called String Interpolation.
This is very useful when you want to say something like “Sally has (some value) apples.” Try out this code at the bottom of your playground:
var apples = 5 println("Sally has (apples) apples")See that? By using the format
(variable name), you can put the value of any variable you want into a String. You can even perform operations inside the parentheses if you want. Add this code to the bottom of your playground:println("Sally has (apples - 5) apples")Nice job! String Interpolation is something that you will be using for just about every program that you write.
Challenge: Now it’s time to combine some of the concepts that you have learned. Create two variables for grades for students in a class: John’s grade (95), and Sam’s Grade (85). Then make an if/else statement that compares John’s and Sam’s grade, and prints out whether John’s grade is less than, greater than, or equal to Sam’s grade. You can do it!
Solution Inside: Solution Show While Loops
While loops are another kind of control flow statement, like the if/else statements you learned earlier. They are similar in the fact that they require a condition to execute.
However, instead of simply executing its code block once, while statements continue to execute the code block as long as its condition remains true. Type out this example at the bottom of your playground.
var secondsLeft = 3 while (secondsLeft > 0) { println(secondsLeft) secondsLeft = secondsLeft - 1 } println("Blast off!")Make sure that you code some way of making sure that the condition becomes false at some point. You do not want to create an infinite loop because it will cause all kinds of problems and your program will not reach anything after the loop.
When you run this, you will see the line
(3 times)on the right hand side, which represents that theprintln()statement is running each time. Since there are multiple values printed out, you have to bring up another window called the Assistant Editor to see them.To do this, go to the top of your screen and select ViewAssistant EditorShow Assistant Editor. In the box marked Console Output, you should be able to see what you printed:
Challenge: Go ahead and try writing your own while loop – for example make a while loop about a cop eating a box of donuts. Remember, no infinite loops!
Solution Inside: Solution Show Break Statement
Say you have some kind of loop in your program, like a while loop, and you want to exit the loop if a specific thing happens. That’s where the
breakcommand comes in. Follow along with this example by writing out the code at the end of your playground.var cokesLeft = 7 var fantasLeft = 4 while(cokesLeft > 0) { println("You have (cokesLeft) Cokes left.") cokesLeft = cokesLeft - 1 if(cokesLeft <= fantasLeft) { break } } println("You stop drinking Cokes.")In this example, you want to keep drinking Coke until there are none left. However, you realize that you also have Fanta in the fridge. You decide you should stop drinking Coke when you have the same amount or less than Fanta because then you would have to start drinking the Fanta to even it out. When this situation occurs, you exit the loop, and thereby stop drinking the Coke.
Challenge: Now it’s your turn to try. Create a while loop that eventually has an ending point – for example a loop about goofing off until the boss stops by. In that loop, add an if statement where you use
breakto exit from the loop.Solution Inside: Solution Show Continue Statement
The continue statement is very similar to the break statement, however, instead of exiting from the loop, it just sends the program back to the beginning of the loop. Type in the example below at the end of your playground.
var numbers = 0 while(numbers <= 10) { if(numbers == 9) { numbers = numbers + 1 continue } println(numbers) numbers = numbers + 1 }As you can see from what the program printed to the console, every number from 0 to 10 was printed except 9 because of the continue statement. It’s too bad that 7 ate 9, but for that reason, you can’t include him in our list.
Challenge: Use continue in your own loop. Find a reason to have a specific value miss commands that other values have to execute and use the continue statement to go to the top of the loop.
Solution Inside: Solution Show Optionals
Sometimes, due to the use of different functions, you don’t know if a variable will have a value or not. When it does not have a value, it is said to contain
nil. This is where optionals come in.Optionals are variables that can either contain a value or contain
nil. Declare an optional and notice you can set it tonil:var optionalNumber: Int? = 5 optionalNumber = nil
The
?is what declares the value as an optional. To figure out if optionals contain a value or are set to nil, you use something called anif letstatement. It looks something like this:if let number = optionalNumber
if letstatements act similar toifstatements. IfoptionalNumbercontains anInt,numberis set to that value and the code inside theif letcurly braces is executed.Optionally, you can set up an
elsestatement to execute ifoptionalNumberhappens to be nil.Challenge: Try this out yourself. Write an
if letstatement foroptionalNumberto print different Strings if it contains a value or if it is nil.Solution Inside: Solution Show Conversion Between Data Types
Let’s see how this can be useful in a program. Optionals can help you to convert between variable types. Try the example below where a
Stringis converted into anInt.var languagesLearned: String = "3" var languagesLearnedNum: Int? = languagesLearned.toInt()
Here, after declaring and initializing
languagesLearnedas aStringwith the value"3", you declare the optionallanguagesLearnedNumand initialize it with the methodtoInt(). Methods are very similar to functions likeprintln()that you learned earlier, except that they are a part of aclass. You will learn more about that later.toInt()is a method that has already been written, so all you have to know is that it takesStringvariables and returns their value inIntform. The reason that you have to set an optional likelanguagesLearnedNumequal to that value is because it has the potential to benil. This occurs if theStringyou are trying to convert does not contain a numerical value, but contains something like"Hello, World".Enter in the following code to test this out:
if let num = languagesLearnedNum { println("It is a number") } else { println("It is not a number") }The
if letstatement tests to see iflanguagesLearnedNumactually contains a value, or if it is nil. If it contains a value, that value is passed tonumand the code inside the curly braces is executed. If not, the code inside of theelsecurly braces is executed.See what happens if you change the
StringinlanguagesLearnedto"Three". The program should print"It is not a number"to the console because languagesLearnedNum will be set tonilwhen the program tries to convert"Three"to anInt.Putting it all together
Challenge: Last one! Try creating your own variables where you try to convert a
Stringto anInt. Then, compare these variables to other variables you set inifstatements that containprintln()statements. Theseprintln()statements should containStrings withStringInterpolation so you can say which values are greater than/less than which values.Solution Inside Show Where To Go From Here?
Here is the finished playground file for this tutorial series so far.
Check out the next part of the series, where you’ll learn how to take your Swift knowledge and make a simple command-line number guessing game!
If you have any questions or comments, please join the forum discussion below!
The post Learn to Code iOS Apps with Swift Tutorial 1: Welcome to Programming appeared first on Codzcook.
We are Learncodz.
Posts
Comments
The Team
Blog Codz Author
Popular Codz Article
-
I rewrite this tutorial from forum.xda-developers.com : The users of Micromax A116 Canvas Hd can now update their handsets to Android 5.0 Lo...
-
Build Your Own URL Shortener With YOURLS
What You'll Be Creating In this tutorial, I'll show you how to install your own open source, PHP-based URL shortener, called YOU... -
Wifi Hacking – WEP – Kali Linux Aircrack-ng suite
Alright, this post is written assuming you have Kali Linux up and running on your computer. If not, here is a post on hacking with kali linu... -
Top 4 Affordable Android One Smartphones from Rs. 6000
If you’re looking for an affordable smartphone to buy this holiday season and aren’t too keen on a Windows Phone, look no further than the A... -
[MOD][4.1 4.2] Extend Phone Storage 1.5, 2.5GB A116 (Other MT6589 Devices on request)
READ EVERYTHING CAREFULLY I Will Not Responsible For Any Brick or Any Problem So Do It At Your Own Risk. This Will Extend your Device's ... -
want to build an chat application..(parse)
Introduction The Parse platform provides a complete backend solution for your mobile application. Our goal is to totally eliminate the nee... -
Distributing iOS Apps With iTunes Connect
Once you've developed your iOS or OS X app, it's time to submit it to Apple for release in the App Store. This process is done throu...
Portfolio
- 2015 at 02:00AM
- 2015 at 02:03AM
- 2015 at 02:07AM
- 2015 at 02:09AM
- 2015 at 03:51AM
- 2015 at 03:57AM
- 2015 at 04:03AM
- 2015 at 04:08AM
- 2015 at 06:38AM
- 2015 at 08:03PM
- 2015 at 08:09PM
- 2015 at 08:13PM
- 2015 at 08:18PM
- 2015 at 08:23PM
- 2015 at 08:32PM
- 2015 at 08:33PM
- 2015 at 08:42PM
- 2015 at 08:50PM
- 2015 at 09:08AM
- 2015 at 09:12AM
- 2015 at 09:20AM
- 2015 at 09:22AM
- 2015 at 09:25AM
- 2015 at 09:27PM
- 2015 at 09:28AM
- 2015 at 09:31PM
- 2015 at 09:34AM
- 2015 at 09:58AM
- 2015 at 10:31AM
- 2015 at 10:45AM
- 2015 at 10:46PM
- 2015 at 10:50AM
- 2015 at 10:57AM
- 2015 at 10:57PM
- 2015 at 10:58AM
- 2015 at 11:04PM
- 2015 at 11:07AM
- 2015 at 11:17AM
- 2015 at 11:20AM
- 2015 at 11:31AM
- 2015 at 11:32AM
- 2015 at 11:33AM
- 2015 at 11:39AM
- 2015 at 11:44AM
- 2015 at 11:45AM
- 2015 at 11:45PM
- 2015 at 11:46PM
- 2015 at 11:50PM
- 2015 at 11:51PM
- 2015 at 11:52AM
- 2015 at 11:57AM
- 2015 at 11:58PM
- 2015 at 12:02PM
- 2015 at 12:04AM
- 2015 at 12:08PM
- 3d maxx
- and
- Android
- android developer
- android developr
- android labels
- android sdk
- android studio
- android tutorial
- android tutorials
- apk
- apple
- application
- apps
- April 19
- April 20
- April 21
- April 22
- April 23
- April 24
- April 25
- At its simplest
- bac
- backtrack
- battery
- biotechnology is technology based on biology - biotechnology harnesses cellular and biomolecular processes to develop technologies and products that help improve our lives and the hea
- Blog
- blogger
- browser
- build an chat application
- C
- chrome app
- command prompt
- designing
- Developing App
- earn money
- games
- hack
- hack Facebook
- Hacking
- help
- How To
- htc
- IFTTT
- intel xdk
- Ios
- ios 8
- ios8
- ips 8
- Java
- Javascript
- lenovo
- mac
- Magento
- Mysql
- new launch
- nexus
- operating system
- OS
- phone
- Photoshop
- Php
- pivotal tracker
- Review
- Reviews
- roms
- root
- Ruby On Rails
- samsung
- sdk
- security
- swift
- Tech. News
- Tools:Tips
- tutorial
- Uncategorized
- unity
- update
- Visual Studio
- windows phone
- Wordpress
- wordpress tutorial