Welcome to FutureAppLaboratory

v=(*^ワ^*)=v

Learning Swift Part 2 - Basics

| Comments

Just some notes after reading Apple’s official online guide. Most code are from the guide, with some modification by me.

===== Full Notes =====

Basics

  • Declaring Constant and Variables
1
2
3
4
    let maximumNumberOfLoginAttempts = 10
    var currentLoginAttempt = 0

    var x = 0.0, y = 0.0, z = 0.0
  • Type Annotations
1
2
3
4
    var welcomeMessgae: String
    welcomeMessgae = "Hello"

    var red, green, blue: Double // Multiple variables defined
  • Naming Constants and Variables
1
2
3
    let π = 3.14159
    let 你好 = "你好世界"
    let 🐶🐮 = "dogcow"

Integers

  • Integer Bounds
1
2
    let minValue = UInt8.min  // minValue is equal to 0, and is of type UInt8
    let maxValue = UInt8.max  // maxValue is equal to 255, and is of type UInt8
  • Int

    • On a 32-bit platform, Int is the same size as Int32.

    • On a 64-bit platform, Int is the same size as Int64.

  • UInt

    • On a 32-bit platform, UInt is the same size as UInt32.

    • On a 64-bit platform, UInt is the same size as UInt64.

  • Floating-Point Numbers

    • Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. T
  • Type Safety and Type Inference

  • Numeric Literals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    let decimalInteger = 17
    let binaryInteger = 0b10001       // 17 in binary notation
    let octalInteger = 0o21           // 17 in octal notation
    let hexadecimalInteger = 0x11     // 17 in hexadecimal notation

    1.25e2          // 125.0
    1.25e-2         // 0.0125
    0xFp2           // 60.0 = 15 x 2 x 2
    0xFp-2          // 3.75 = 15 x 0.5 x 0.5

    // Can have additional formatting literal (like Ruby)

    let paddedDouble = 000123.456
    let oneMillion = 1_000_000
    let justOverOneMillion = 1_000_000.000_000_1
  • Integer Conversion
1
2
3
4
5
6
7
8
9
10
11
    let cannotBeNegative: UInt8 = -1
    // UInt8 cannot store negative numbers, and so this will report an error
    let tooBig: Int8 = Int8.max + 1
    // Int8 cannot store a number larger than its maximum value,
    // and so this will also report an error

    // conversion must be explicit

    let twoThousand: UInt16 = 2_000
    let one: UInt8 = 1
    let twoThousandAndOne = twoThousand + UInt16(one)
  • Integer and Floating-Point Conversion
1
2
3
4
5
6
7
    let three = 3
    let pointOneFourOneFiveNine = 0.14159
    let pi = Double(three) + pointOneFourOneFiveNine
    // pi equals 3.14159, and is inferred to be of type Double

    let integerPi = Int(pi)
    // integerPi equals 3, and is inferred to be of type Int
  • Type Aliases
1
2
3
    typealias AudioSample = UInt16
    var maxAmplitudeFound = AudioSample.min
    // maxAmplitudeFound is now 0
  • Boolean
1
2
3
4
5
6
7
8
9
    let orangesAreOrange = true
    let turnipsAreDelicious = false

    if turnipsAreDelicious {
        println("Mmm, tasty turnips!")
    } else {
        println("Eww, turnips are horrible.")
    }
    // prints "Eww, turnips are horrible."

Tuples

  • Sample
1
2
    let http404Error = (404, "Not Found")
    // http404Error is of type (Int, String), and equals (404, "Not Found")
  • Decompose a tuple
1
2
3
4
5
    let (statusCode, statusMessage) = http404Error
    println("The status code is \(statusCode)")
    // prints "The status code is 404"
    println("The status message is \(statusMessage)")
    // prints "The status message is Not Found"
  • Ignore some value when decomposing
1
2
3
    let (justTheStatusCode, _) = http404Error
    println("The status code is \(justTheStatusCode)")
    // prints "The status code is 404"
  • Access by index
1
2
3
4
    println("The status code is \(http404Error.0)")
    // prints "The status code is 404"
    println("The status message is \(http404Error.1)")
    // prints "The status message is Not Found"

Optionals

  • Sample
1
2
3
    let possibleNumber = "123"
    let convertedNumber = possibleNumber.toInt()
    // convertedNumber is inferred to be of type "Int?", or "optional Int"
  • nil
1
2
3
4
5
6
7
    var serverResponseCode: Int? = 404
    // serverResponseCode contains an actual Int value of 404
    serverResponseCode = nil
    // serverResponseCode now contains no value

    var surveyAnswer: String?
    // surveyAnswer is automatically set to nil
  • If Statements and Forced Unwrapping
1
2
3
4
    if convertedNumber != nil {
        println("convertedNumber has an integer value of \(convertedNumber!).")
    }
    // prints "convertedNumber has an integer value of 123."
  • Optional Binding
1
2
3
4
5
6
7
8
9
10
    if let constantName = someOptional {
        statements
    }

    if let actualNumber = possibleNumber.toInt() {
        println("\(possibleNumber) has an integer value of \(actualNumber)")
    } else {
        println("\(possibleNumber) could not be converted to an integer")
    }
    // prints "123 has an integer value of 123"
  • Implicitly Unwrapping Optionals (Accessing an implicitly unwrapped optional when it does not contain a value will trigger a RTE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    let possibleString: String? = "An optional string."
    let forcedString: String = possibleString! // requires an exclamation mark

    let assumedString: String! = "An implicitly unwrapped optional string."
    let implicitString: String = assumedString // no need for an exclamation mark

    if assumedString != nil {
        println(assumedString)
    }
    // prints "An implicitly unwrapped optional string."

    if let definiteString = assumedString {
        println(definiteString)
    }
    // prints "An implicitly unwrapped optional string."
  • Assertions

  • Debugging with Assertions

1
2
3
    let age = -3
    assert(age >= 0, "A person's age cannot be less than zero")
    // this causes the assertion to trigger, because age is not >= 0

Comments