Swift is Apple's brand new programming language, published in the 2014 WWDC (Apple developer Conference).
With the swift language release, Apple has also released an excellent Swift reference guide, which is strongly recommended here.
But this learning guide is long and thin! So if you don't have a lot of time and just want to learn swift quickly, then this tutorial is for you.
This swift tutorial will take about 25 minutes to learn and give a quick look at the swift language, including variables, control streams, classes, and more.
For this swift tutorial, you need the latest version of Xcode (Xcode 6.1.1 is used when writing this swift tutorial). This tutorial does not require any swift and objective-c experience, but it can be useful for understanding and learning if you have some programming experience.
Note: Make sure you have the latest Xcode (check in the Mac App Store to make sure). Swift is changing rapidly and we are doing everything we can to update this tutorial for each beta release; The code may not work correctly in an older version of Xcode or in a pre-release version.
Playgrounds Introduction
start Xcode 6 and go to File\new\file. Select Ios\source\playground and click Next.
Name the file as Swifttutorial.playground and click Create and save it in a convenient place. Delete other unused files to keep a clean file directory.
Playground is a file type and allows you to test the Swift code to see the results of each row in the sidebar. For example: Add the following line to playground:
Let Tutorialteam = 60
Let Editorialteam = 17
Let Totalteam = Tutorialteam + editorialteam
When you write input to these lines, you see the results of each row on the side bar. Is it convenient?
Playgrounds is a good way to learn swift (such as this swift tutorial) to experiment with new APIs, prototype code or algorithms, or visualize drawing code. In the remainder of this swift tutorial, you will use playground.
Note: At this point, it is recommended that you drag the playground file (swifttutorial.playground) to the OS X dock.
In this way, you can test some code, and swift uses this file as a fast register. Of course, for this job, there must be a playground in one place and not be able to move it casually.
Swift Variable vs constant
Try adding the following line to the bottom of the playground:
When you join this line, you will find an error. This is because Totalteam is a constant, which means that its value will never change. The keyword let declaration constant is used in swift.
If you want Totalteam to be a variable, its value can be changed at any time-declaring it requires a different keyword: var.
To do this, initialize Totalteam use the following line to replace the previous declaration:
var totalteam = Tutorialteam + editorialteam
Now it's working! It might be like you think, "Why not use Var to declare everything, without having so many restrictions?" ”
Well, it's best to use let to declare a constant, because it allows the compiler to optimize. So remember: Whenever possible, use let to declare constants!
explicit and inferred input
So far, the types of these constants and variables have not been explicitly set, because the compiler has enough information to automatically infer it.
For example, set Tutorialteam to 56 and the compiler knows that 56 is an int type, so it automatically sets the Oftutorialteam type to int.
However, you can also set an explicit type if you want to. Try to set the type of Tutorialteam by setting the following line:
Let Tutorialteam:int = 60
If you do not know the explicit type, or have the compiler infer the type and set it automatically. It's a good idea to let the compiler infer the type automatically, because this is one of Swift's main strengths: simplicity, easy code reading.
Because of this, switch back to the previous line using inferred input (automatic recognition type):
Copy Code code as follows:
Swift basic types and control flow
So far, you've seen an Int explanation, which is an example of Swift's use of integer numeric types, but there's more.
Try using some basic types, each of which is pasted at the bottom of the playground.
Floats and doubles
Let priceinferred = 19.99
Let priceexplicit:double = 19.99
There are two kinds of decimal point values, such as Float and Double. Double has more precision, and the default is a decimal value. This means that the priceinferred is of type Double.
Bools
Let onsaleinferred = True
Let Onsaleexplicit:bool = False
Note that the use of True/false as a Boolean value in Swift (yes/no is used in objective-c, so they are somewhat different).
Strings
Let nameinferred = "Whoopie cushion"
Let nameexplicit:string = "Whoopie cushion"
The string is as you would expect, but note that it is no longer like using the @ symbol in OBJECTIVE-C.
if statement 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 in other programming languages. The parentheses of the condition are optional, and curly braces are required, even if there are only 1 lines of statements.
An example of a new technique called string interpolation is described here. Whenever you want to replace something in the string in swift, just use this syntax: \ (expression).
At this point, you can see the results of the println in the sidebar, which may be difficult to see due to limited space. To view the output, move the mouse to the row, and click the Eyeball (icon) that appears:
There is also a way to see the output. Go to the main menu of Xcode and select View\assistant editor\show Assistant Editor.
The assistant editor will tell you the results of any println statements in your code and display the resulting values in a convenient place, which is often easier than using the mouse to place each row.
Classes and methods
creating classes and methods in swift development is the most common practice, let's see!
First, delete everything in the playground file so that you can start writing new code in a clean file.
Next, you will create a tip calculator class to help depict the restaurant. Add a small piece of code one at a time, which is explained Step-by-step.
1
Class Tipcalculator {
}
To create a class, simply enter the name of the class after the class keyword. The body of the class then uses a curly brace.
If you are inheriting from another class, use a: symbol followed by the name of the inherited class. Note that you do not necessarily need to inherit (unlike in Objective-c, where you must inherit something like NSObject or derive from NSObject).
Add the following code within curly braces:
2
Let Total:double
Let Taxpct:double
Let Subtotal:double
There are some errors when you add these, but don't worry, they will be resolved soon.
This is how you create a property in a class-the same way you create a variable or constant. Here, you will create a property of three constants – one is the total amount of the bill (after-tax), a tax percentage applied to the bill, and a subtotal for the bill (pre-tax).
Note that when declaring them, the declaration must set the initial value for them, or at the time of initialization-that is why there are errors at the moment. If you do not want to set initial values for properties, you must declare them as optional (more, in future tutorials).
Add code after the previously created block (in curly braces):
3
Init (total:double, taxpct:double) {
Self.total = Total
self.taxpct = taxpct
Subtotal = total/(taxpct + 1)
}
This creates an initializer for the class and uses two parameters. The name of the initializer in Swift is always init– but can have multiple (if necessary) parameters that can be used differently.
Note that the parameter is already used here for this method, which is the same as the name of the property of this class. Because of this, it is necessary to distinguish between the two by prefixing themselves to attributes
Note that there is no name conflict because there is no subtotal property, and you do not need to add the Self keyword because the compiler can infer it automatically.
Note: If you want to know subtotal = total/(tippct + 1) The calculation comes from:
(Subtotal * taxpct) + subtotal = Total
Subtotal * (taxpct + 1) = Total
Subtotal = total/(taxpct + 1)
Add code after the previous code block (in curly braces):
4
Func calctipwithtippct (tippct:double)-> Double {
Return subtotal * tippct
}
To define a method, you can use the Func keyword. It then lists the parameters (must be explicitly typed), adds the-> symbol, and finally lists the return type.
This is a function that determines the amount of the tip, which is simple enough to get the result by multiplying the percentage by the subtotal.
Add code after the previous block (in curly braces):
5
Func printpossibletips () {
println ("15%: \ (calctipwithtippct (0.15))")
println ("18%: \ (calctipwithtippct (0.18))")
println ("20%: \ (calctipwithtippct (0.20))")
}
This is the new method used to print out three possible tips.
Note that when you call an instance method of a class, the first argument does not need to be named (but the rest).
Also, be aware of how string interpolation is not limited to print output variables. You can use a variety of complex method calls and operations, but need to be properly inline!
Add the following code to the bottom of the playground (after curly braces):
6
Let Tipcalc = Tipcalculator (total:33.25, taxpct:0.06)
Tipcalc.printpossibletips ()
Finally, create an instance of the tip calculator and call the method to print the possible tip.
This is all the code for the entire playground file so far:
1
Class Tipcalculator {
2
Let Total:double
Let Taxpct:double
Let Subtotal:double
3
Init (total:double, taxpct:double) {
Self.total = Total
self.taxpct = taxpct
Subtotal = total/(taxpct + 1)
}
4
Func calctipwithtippct (tippct:double)-> Double {
Return subtotal * tippct
}
5
Func printpossibletips () {
println ("15%: \ (calctipwithtippct (0.15))")
println ("18%: \ (calctipwithtippct (0.18))")
println ("20%: \ (calctipwithtippct (0.20))")
}
}
6
Let Tipcalc = Tipcalculator (total:33.25, taxpct:0.06)
Tipcalc.printpossibletips ()
To view the results of the Assistant editor:
Arrays and for loops
Currently, there are some repetitions in the above code, because the call Calctipwithtotalmethod several times to calculate the different proportions of the tip. This can be done by using an array to reduce duplication.
Replace Printpossibletips as follows:
Let possibletipsinferred = [0.15, 0.18, 0.20]; Tip Scale Array List
Let possibletipsexplicit:[double] = [0.15, 0.18, 0.20]; Tip Scale Array List
This demonstrates creating an array of double types, with both inferences and an example of an explicit type (created for demonstration purposes only). Note that [Double] is a shortcut to array<double>.
Then add the following lines:
For Possibletip in possibletipsinferred {
println ("\ (possibletip*100)%: \ (calctipwithtippct (Possibletip))")
}
Enumerations iterate through an array of items similar to objective-c, quick enumerations-note that parentheses are not required!
You can write loops like this (but the current syntax is the preferred style):
For I in 0..< possibletipsinferred.count {
Let Possibletip = Possibletipsinferred[i]
println ("\ (possibletip*100)%: \ (calctipwithtippct (Possibletip))")
}
.. The < operator is a non-package range operator and does not include the upper bound value. There is also an operator ... It is inclusive.
Arrays use the Count property to calculate the total number of items in an array. You can also find specific items in an array, defined by the syntax Arrayname[index], as seen here.
Dictionaries
Let's make the last change to the tip calculator. Instead of simply printing out tips, you can return the results to a dictionary. This makes the results easier to display in some kind of user interface for the application.
Delete the Printpossibletips method and replace it with the following code:
1
Func returnpossibletips ()-> [int:double] {
Let possibletipsinferred = [0.15, 0.18, 0.20]
Let possibletipsexplicit:[double] = [0.15, 0.18, 0.20]
2
var retval = [Int:double] ()
For Possibletip in possibletipsinferred {
Let intpct = Int (possibletip*100)
3
RETVAL[INTPCT] = calctipwithtippct (Possibletip)
}
return retval
}
This will get an error in the playground, but it will be solved soon.
Let's start with the code snippet from the above section:
Here, the tag method returns the dictionary, where the key is int (the tip percentage is int, such as 15 or 20), and the value is a Double (the calculated tip). Note that [int:double] is just a shortcut to Dictionary<int, double>.
This shows how to create an empty dictionary. Note that because you are in this dictionary, you need to declare it as a variable (using VAR) instead of a constant (using let). Otherwise, you will get a compilation error.
This is the setting of the project in the dictionary. As you can see, it is similar to the literal syntax of objective-c.
Finally, modify the last line of the playground file to invoke this method (this fix error):
Tipcalc.returnpossibletips ()
When playground evaluates the calculation, it should be possible to see the result as a dictionary (click on the enlarged view of the eyeball and use the down arrow to expand).
That's it-congratulations, a fully functional tip calculator, written with Swift, has been completed!
The following is the code content for all final playground files in this tutorial:
1
Class Tipcalculator {
2
Let Total:double
Let Taxpct:double
Let Subtotal:double
3
Init (total:double, taxpct:double) {
Self.total = Total
self.taxpct = taxpct
Subtotal = total/(taxpct + 1)
}
4
Func calctipwithtippct (tippct:double)-> Double {
Return subtotal * tippct
}
1
Func returnpossibletips ()-> [int:double] {
Let possibletipsinferred = [0.15, 0.18, 0.20]
Let possibletipsexplicit:[double] = [0.15, 0.18, 0.20]
2
var retval = [Int:double] ()
For Possibletip in possibletipsinferred {
Let intpct = Int (possibletip*100)
3
RETVAL[INTPCT] = calctipwithtippct (Possibletip)
}
return retval
}
}
6
Let Tipcalc = Tipcalculator (total:33.25, taxpct:0.06)
Tipcalc.returnpossibletips ()
}