Swift Quick Start Tutorial: 30 minutes to play Swift

Source: Internet
Author: User
Tags sunrise and sunset times

In general, the first program in a programming language tutorial should print "Hello, World" on the screen. In Swift, one line of code can be implemented:
println ("Hello, World")

If you write a C or objective-c code, you should be familiar with this form-in Swift, this line of code is a complete program. You do not need to import a separate library for input or output or string processing. The code in the global scope is automatically used as the entry point for the program, so you don't need the main function. You also don't need to write a semicolon at the end of each statement.

This tutorial will give you an initial understanding of Swift with a series of programming examples, and don't worry if you don't understand anything-any of the sections described in this chapter will be explained in more detail later in this chapter.

Note: To get the best experience, use the Code preview feature in Xcode. The Code preview feature lets you edit the code and see the results of the run in real time.
Simple values

Use let to declare constants, and use Var to declare variables. A constant value does not need to be fetched at compile time, but you can only assign it once. That means you can use represented to represent a value: You only have to decide once, but you need to use it many times.

    1. var myvariable = 42
    2. myvariable = 50
    3. Let myconstant = 42

The types of constants or variables must be the same as the values you assign to them. However, the declaration-time type is optional and the compiler automatically infers the type when the declaration is assigned at the same time. In the example above, the compiler infers that myvariable is an integer because its initial value is an integer.

If the initial value does not provide enough information (or no initial value), then you need to declare the type after the variable, separated by a colon.

    1. Let Implicitinteger = 70
    2. Let implicitdouble = 70.0
    3. Let explicitdouble:double = 70
Exercise: Create a constant, explicitly specifying a type of float and specifying an initial value of 4.

Values are never implicitly converted to other types. If you need to convert a value to another type, explicitly convert it.

    1. Let label = "the width is"
    2. Let width = 94
    3. Let Widthlabel = label + String (width)
Exercise: Delete The string from the last line, what is the error message?

There is a simpler way to convert a value to a string: write the value in parentheses, and write a backslash before the parentheses. For example:

    1. Let apples = 3
    2. Let oranges = 5
    3. Let applesummary = "I has \ (apples) apples."
    4. Let fruitsummary = "I had \ (apples + oranges) pieces of fruit."
Exercise: Use \ () to convert a floating-point calculation into a string, and add someone's name and say hello to him.

Use square brackets [] to create arrays and dictionaries, and use subscripts or keys to access elements.

    1. var shoppinglist = ["Catfish", "water", "tulips", "Blue paint"]
    2. SHOPPINGLIST[1] = "Bottle of Water"
    3. var occupations = ["Malcolm": "Captain", "Kaylee": "Mechanic",]
    4. occupations["Jayne"] = "Public Relations"

To create an empty array or dictionary, use the initialization syntax.

    1. Let Emptyarray = string[] ()
    2. Let emptydictionary = dictionary<string, float> ()

If the type information can be inferred, you can use [] and [:] To create an empty array and an empty dictionary-just as you would declare a variable or pass arguments to a function.

    1. Shoppinglist = []//GO shopping and buy something
Control flow

Use if and switch to perform conditional operations, using for-in, for, while, and do-while for looping. Wrapping conditions and loop variable parentheses can be omitted, but curly braces on the body of the statement are required.

    1. Let individualscores = [75, 43, 103, 87, 12]
    2. var Teamscore = 0
    3. For score in Individualscores {
    4. If score > 50 {
    5. Teamscore + = 3
    6. } else {
    7. Teamscore + = 1
    8. }
    9. }
    10. Teamscore

In an If statement, the condition must be a Boolean expression--like if score {...} This code is wrong.

You can use if and let together to handle the case of missing values. The values of some variables are optional. An optional value may be a specific value or nil, indicating that the value is missing. It is optional to add a question mark after the type to mark the value of the variable.

    1. var optionalstring:string? = "Hello"
    2. Optionalstring = Nil
    3. var optionalname:string? = "John Appleseed"
    4. var greeting = "Hello!"
    5. If let name = optionalname {
    6. Greeting = "Hello, \ (name)"
    7. }
Exercise: What would it be to change optionalname to nil,greeting? Add an Else statement that assigns a different value to greeting when Optionalname is nil.

If the optional value of the variable is nil, the condition is judged to be false and the code in the curly braces is skipped. If it is not nil, the value is assigned to the constant behind let, so the value can be used in the code block.

Switch supports any type of data and various comparison operations-not just integers, but test equality.

    1. Let vegetable = "red pepper"
    2. Switch Vegetable {
    3. Case "Celery":
    4. Let vegetablecomment = "Add some raisins and make ants on a log."
    5. Case "cucumber", "watercress":
    6. Let vegetablecomment = "so would make a good tea sandwich."
    7. Case Let X where X.hassuffix ("Pepper"):
    8. Let vegetablecomment = "is it a spicy \ (x)?"
    9. Default
    10. Let vegetablecomment = "everything tastes good in soup."
    11. }
Exercise: Delete the default statement and see what is wrong with it?

After you run the clause that matches in the switch, the program exits the switch statement and does not continue running down, so you do not need to write a break at the end of each clause.

You can use for-in to traverse a dictionary, which requires two variables to represent each key-value pair.

    1. Let interestingnumbers = [
    2. "Prime": [2, 3, 5, 7, 11, 13],
    3. "Fibonacci": [1, 1, 2, 3, 5, 8],
    4. "Square": [1, 4, 9, 16, 25],
    5. ]
    6. var largest = 0
    7. For (kind, numbers) in Interestingnumbers {
    8. For number in numbers {
    9. If number > largest {
    10. largest = number
    11. }
    12. }
    13. }
    14. Largest
Exercise: Add another variable to record which type of number is the largest.

Use while to repeatedly run a piece of code until the condition is not met. The loop condition can be at the beginning as well as at the end.

    1. var n = 2
    2. While n < 100 {
    3. n = n * 2
    4. }
    5. N
    6. var m = 2 Do {
    7. m = m * 2
    8. } While M < 100
    9. M

You can use it in loops: To represent a range, or to use a traditional notation, the two are equivalent:

    1. var firstforloop = 0
    2. For I in 0..3 {
    3. Firstforloop + = i
    4. }
    5. Firstforloop
    6. var secondforloop = 0
    7. for var i = 0; I < 3; ++i {
    8. Secondforloop + = 1
    9. } secondforloop

Use.. The created range does not contain an upper bound and needs to be used if you want to include ....

Functions and closures

Use Func to declare a function, using the name and arguments to invoke the function. Use to specify the function return value.

    1. Func greet (name:string, day:string), String {
    2. Return "Hello \ (name), today is \ (day)."
    3. }
    4. Greet ("Bob", "Tuesday")
Exercise: Remove the day parameter and add a parameter to indicate what lunch was eaten today.

Use a tuple to return multiple values.

    1. Func getgasprices () (double, double, double) {
    2. Return (3.59, 3.69, 3.79)
    3. }
    4. Getgasprices ()

The number of arguments to a function is variable, and an array is used to obtain them:

    1. Func sumof (Numbers:int ...), Int {
    2. var sum = 0
    3. For number in numbers {
    4. Sum + = number
    5. }
    6. return sum
    7. }
    8. Sumof ()
    9. Sumof (42, 597, 12)
Exercise: Write a function that calculates the mean of the parameter.

Functions can be nested. Nested functions can access variables of the outer function, and you can use nested functions to refactor a function that is too long or too complex.

    1. Func Returnfifteen (), Int {
    2. var y = ten func Add () {
    3. Y + = 5
    4. }
    5. Add ()
    6. Return y
    7. }
    8. Returnfifteen ()

A function is a class citizen, which means that the function can be the return value of another function.

    1. Func Makeincrementer ()-(int-int) {
    2. Func AddOne (number:int), Int {
    3. Return 1 + number
    4. }
    5. Return AddOne
    6. }
    7. var increment = Makeincrementer ()
    8. Increment (7)

Functions can also be passed as arguments to another function.

    1. Func hasanymatches (list:int[], condition:int-bool), BOOL {
    2. For item in list {
    3. If condition (item) {
    4. return True
    5. }
    6. }
    7. return False
    8. }
    9. Func Lessthanten (number:int), Bool {
    10. Return number < 10
    11. }
    12. var numbers = [20, 19, 7, 12]
    13. Hasanymatches (Numbers, Lessthanten)

function is actually a special kind of closure, you can use {} to create an anonymous closure. Use in to split the parameter and return the type.

    1. Numbers.map ({
    2. (Number:int), Int in
    3. Let result = 3 * number
    4. return result
    5. })
exercise: Rewrite closures, return 0 for all odd numbers.

There are many ways to create closures. If a type of closure is known, such as a callback function, you can ignore the type and return value of the parameter. A single statement closure will return the value of its statement as a result.

You can refer to parameters by parameter location instead of parameter name-this method is very useful in very short closures. When a closure is passed to a function as the last argument, it can be followed directly by the parentheses.

    1. Sort ([1, 5, 3, 2]) {$ > $}
Objects and classes

Use class and class names to create a class. The only difference between the declaration of a property in a class and a constant, variable declaration is that their context is a class. Similarly, methods and function declarations are the same.

    1. Class Shape {
    2. var numberofsides = 0
    3. Func simpledescription (), String {
    4. Return "A shape with \ (numberofsides) sides."
    5. }
    6. }
Exercise: Use let to add a constant property, and then add a method that receives a parameter.

To create an instance of a class, insert parentheses after the class name. Use point syntax to access the properties and methods of an instance.

    1. var shape = shape ()
    2. Shape.numberofsides = 7
    3. var shapedescription = shape.simpledescription ()

This version of the shape class lacks something important: a constructor to initialize the class instance. Use init to create a constructor.

    1. Class Namedshape {
    2. var numberofsides:int = 0
    3. var name:string
    4. Init (name:string) {
    5. Self.name = Name
    6. }
    7. Func simpledescription (), String {
    8. Return "A shape with \ (numberofsides) sides."
    9. }
    10. }

Note that self is used to differentiate instance variables. When you create an instance, pass in the parameters of the constructor to the class as if it were passed in as a function parameter. Each property needs to be assigned-whether it is declared (like numberofsides) or through a constructor (like name).

If you need to do some cleanup before deleting the object, create a destructor using Deinit.

Subclasses are defined by adding the name of the parent class after their class name, separated by a colon. You do not need a standard root class when creating a class, so you can ignore the parent class.

Subclass if you want to override the method of the parent class, you need to use the override tag--if you override the parent method without adding override, the compiler will error. The compiler will also detect if the override tag's method is actually in the parent class.

    1. Class Square:namedshape {
    2. var sidelength:double
    3. Init (sidelength:double, name:string) {
    4. Self.sidelength = Sidelength
    5. Super.init (Name:name)
    6. Numberofsides = 4
    7. }
    8. Func area (), Double {
    9. Return sidelength * sidelength
    10. }
    11. Override Func Simpledescription (), String {
    12. Return "A square with sides of length \ (sidelength)."
    13. }
    14. }
    15. Let test = Square (sidelength:5.2, Name: "My Test Square")
    16. Test.area ()
    17. Test.simpledescription ()
Exercise: Create another subclass of Namedshape Circle, the constructor receives two parameters, one is the radius, one is the name, and the area and describe methods are implemented.

Properties can have getter and setter.

    1. Class Equilateraltriangle:namedshape {
    2. var sidelength:double = 0.0
    3. Init (sidelength:double, name:string) {
    4. Self.sidelength = Sidelength
    5. Super.init (Name:name)
    6. Numberofsides = 3
    7. }
    8. var perimeter:double {
    9. get {
    10. Return 3.0 * Sidelength
    11. }
    12. set {
    13. Sidelength = newvalue/3.0
    14. }
    15. }
    16. Override Func Simpledescription (), String {
    17. Return "an equilateral triagle with sides of length \ (sidelength)."
    18. }
    19. }
    20. var triangle = Equilateraltriangle (sidelength:3.1, Name: "A triangle")
    21. Triangle.perimeter
    22. Triangle.perimeter = 9.9
    23. Triangle.sidelength

In the setter of perimeter, the name of the new value is newvalue. You can display the settings after set a name.

Note that the constructor for the Equilateraltriangle class performs three steps:

    1. Set property values for a subclass declaration
    2. Calling the constructor of the parent class
    3. Changes the property value of the parent class definition. Other tasks such as calling methods, getters, and setters can also be done at this stage.

If you do not need to calculate a property but need to run some code before setting a new value, use Willset and Didset.

For example, the following class ensures that the side length of a triangle is always the same length as the sides of a square.

    1. Class Triangleandsquare {
    2. var Triangle:equilateraltriangle {
    3. Willset {
    4. Square.sidelength = Newvalue.sidelength
    5. }
    6. }
    7. var Square:square {
    8. Willset {
    9. Triangle.sidelength = Newvalue.sidelength
    10. }
    11. }
    12. Init (size:double, name:string) {
    13. Square = Square (sidelength:size, Name:name)
    14. Triangle = Equilateraltriangle (sidelength:size, Name:name)
    15. }
    16. }
    17. var triangleandsquare = Triangleandsquare (size:10, Name: "Another Test shape")
    18. TriangleAndSquare.square.sideLength
    19. TriangleAndSquare.triangle.sideLength
    20. Triangleandsquare.square = Square (sidelength:50, name: "Larger square")
    21. TriangleAndSquare.triangle.sideLength

There is an important difference between a method in a class and a general function, the parameter name of the function is used only inside the function, but the parameter name of the method needs to be explicitly stated at the time of the call (except for the first argument). By default, the parameter name of the method is the same as its name inside the method, but you can also define a second name, which is used inside the method.

    1. Class Counter {
    2. var count:int = 0
    3. Func IncrementBy (Amount:int, Numberoftimes times:int) {
    4. Count + = Amount * times
    5. }
    6. }
    7. var counter = counter ()
    8. Counter.incrementby (2, Numberoftimes:7)

When working with optional values for variables, you can add them before actions such as methods, properties, and sub-scripts. If the previous value is nil, then everything behind will be ignored and the entire expression returns nil. Otherwise, everything after that will be run. In both cases, the value of the entire expression is also an optional value.

    1. Let Optionalsquare:square? = Square (sidelength:2.5, name: "Optional Square")
    2. Let Sidelength = Optionalsquare?. Sidelength
Enumerations and struct bodies

Use an enum to create an enumeration. Just like the class and all other named types, enumerations can contain methods.

    1. Enum Rank:int {
    2. Case ACE = 1
    3. Case A, three, four, Five, Six, Seven, Eight, Nine, Ten
    4. Case Jack, Queen, King.
    5. Func simpledescription (), String {
    6. Switch Self {
    7. Case. Ace:
    8. Return "Ace"
    9. Case. Jack:
    10. Return "Jack"
    11. Case. Queen:
    12. Return "Queen"
    13. Case. King:
    14. Return "King"
    15. Default
    16. Return String (Self.toraw ())
    17. }
    18. }
    19. }
    20. Let Ace = Rank.ace
    21. Let Acerawvalue = Ace.toraw ()
Exercise: Write a function that compares two rank values by comparing their original values.

In the example above, the type of the enum original value is int, so you just need to set the first original value. The remaining raw values are assigned in order. You can also use a string or a floating-point number as the original value of the enumeration.

Use the Toraw and Fromraw functions to convert between the original value and the enumeration value.

    1. If Let Convertedrank = Rank.fromraw (3) {
    2. Let threedescription = Convertedrank.simpledescription ()
    3. }

The member value of an enumeration is an actual value and is not an alternative expression of the original value. In fact, if the original value doesn't make sense, you don't need to set it.

    1. Enum Suit {
    2. Case Spades, Hearts, Diamonds, Clubs
    3. Func simpledescription (), String {
    4. Switch Self {
    5. Case. Spades:
    6. Return "Spades"
    7. Case. Hearts:
    8. Return "Hearts"
    9. Case. Diamonds:
    10. Return "Diamonds"
    11. Case. Clubs:
    12. Return "clubs"
    13. }
    14. }
    15. }
    16. Let hearts = Suit.hearts
    17. Let heartsdescription = Hearts.simpledescription ()
Exercise: Add a color method to suit, return "black" to spades and clubs, and return "red" to Hearts and diamonds.

Note that there are two ways to refer to a Hearts member: When assigning a value to a Hearts constant, the enumeration member Suit.hearts needs to be referenced by its full name because the constant does not explicitly specify a type. In switch, enumeration members use abbreviations. Hearts to reference, because the value of self is already known to be a suit. You can use abbreviations in cases where the variable type is known.

Use a struct to create a struct body. Structs and classes have many of the same places, such as methods and constructors. One of the biggest differences between the structures is that the struct is a value, and the class is a reference.

    1. struct Card {
    2. var Rank:rank
    3. var suit:suit
    4. Func simpledescription (), String {
    5. Return "The \ (Rank.simpledescription ()) of \
    6. (Suit.simpledescription ()) "
    7. }
    8. }
    9. Let Threeofspades = Card (rank:. Three, suit:. Spades)
    10. Let threeofspadesdescription = Threeofspades.simpledescription ()
Exercise: Add a method to the card, create a full deck of cards, and match the rank and suit of each card.

An instance of an enumeration member can have an instance value. Instances of the same enumeration member can have different values. When you create an instance, the value is passed in. The instance value and the original value are different: The original value of the enumeration member is the same for all instances, and you are setting the original value when you define the enumeration.

For example, consider the time to get sunrise and sunset from the server. The server returns a normal result or error message.

    1. Enum Serverresponse {
    2. Case Result (String, String)
    3. Case Error (String)
    4. }
    5. Let success = Serverresponse.result ("6:00pm", "8:09 PM")
    6. Let failure = Serverresponse.error ("Out of cheese.")
    7. Switch Success {
    8. Case Let. Result (Sunrise, Sunset):
    9. Let Serverresponse = "Sunrise are at \ (Sunrise) and sunset are at \ (sunset)."
    10. Case Let. Error (Error):
    11. Let Serverresponse = "Failure ... \ (Error)"
    12. }
Exercise: Add a third case to serverresponse and switch.

Note How to extract the sunrise and sunset times from the Serverresponse.

Interfaces and extensions

Use protocol to declare an interface.

    1. Protocol Exampleprotocol {
    2. var simpledescription:string {Get}
    3. Mutating func adjust ()}

Classes, enumerations, and structs can all implement interfaces.

    1. Class Simpleclass:exampleprotocol {
    2. var simpledescription:string = "A very simple class."
    3. var anotherproperty:int = 69105
    4. Func Adjust () {
    5. Simpledescription + = "Now 100% adjusted."
    6. }
    7. }
    8. var a = Simpleclass ()
    9. A.adjust ()
    10. Let adescription = A.simpledescription
    11. struct Simplestructure:exampleprotocol {
    12. var simpledescription:string = "A simple structure" mutating func adjust () {
    13. Simpledescription + = "(adjusted)"
    14. }
    15. }
    16. var B = simplestructure ()
    17. B.adjust ()
    18. Let bdescription = B.simpledescription
Exercise: Write an enumeration that implements this interface.

Note When declaring simplestructure, the mutating keyword is used to mark a method that modifies a struct. The Simpleclass declaration does not need to tag any methods because the methods in the class often modify the class.

Use extension to add functionality to an existing type, such as adding a method that calculates a property. You can use extensions to add protocols to any type, even types that you import from external libraries or frameworks.

    1. Extension Int:exampleprotocol {
    2. var simpledescription:string {
    3. Return "the number \ (self)"
    4. }
    5. Mutating func adjust () {
    6. Self + = 42
    7. }
    8. }
    9. 7.simpleDescription
Exercise: Write an extension to the double type and add the Absolutevalue function.

You can use the interface name as you would with other named types-for example, to create a collection of objects that have different types but implement an interface. Methods that are defined outside the interface are not available when you are dealing with a type that is the value of an interface.

    1. Let Protocolvalue:exampleprotocol = A//Protocolvalue.anotherproperty
    2. Protocolvalue.simpledescription//Uncomment to see the error

Even though the type of the Protocolvalue variable runtime is simpleclass, the compiler will take its type as Exampleprotocol. This means that you cannot invoke a method or property that the class implements outside of the interface it implements.

Generic type

Write a name in angle brackets to create a generic function or type.

    1. Func repeat<itemtype> (Item:itemtype, Times:int), itemtype[] {
    2. var result = itemtype[] ()
    3. For I in 0..times {
    4. Result + = Item
    5. }
    6. return result
    7. }
    8. Repeat ("Knock", 4)

You can also create generic classes, enumerations, and struct-bodies.

    1. Reimplement the Swift standard library ' s optional type
    2. Enum Optionalvalue<t> {
    3. Case None Case Some (T)
    4. }
    5. var possibleinteger:optionalvalue<int> =. None
    6. Possibleinteger =. Some (100)

Use the Where to specify a list of requirements after the type name-for example, to qualify a type that implements a protocol, you need to qualify two types to be the same, or to qualify a class that must have a specific parent class.

    1. Func anycommonelements <t, U where t:sequence, U:sequence, t.generatortype.element:equatable, T.GeneratorType.Eleme NT = = u.generatortype.element> (Lhs:t, rhs:u), Bool {
    2. For Lhsitem in LHS {
    3. For Rhsitem in RHS {
    4. if Lhsitem = = Rhsitem {
    5. return True
    6. }
    7. }
    8. }
    9. return False
    10. }
    11. Anycommonelements ([1, 2, 3], [3])
Exercise: Modify the Anycommonelements function to create a function that returns an array with the contents of a common element of two sequences.

For simplicity, you can ignore where, just write the interface or class name after the colon. The <T:Equatable> and <t where t:equatable> are equivalent.

Swift Quick Start Tutorial: 30 minutes to play Swift

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.