Swift The Basics

some notes while reading the part of basics of swift documentation
i want to learn swift and improve my ability to read development documentation by writing this note everyday

swift documentation link

variables and constants

  • you can declare constants with the let keyword and variables with the var keyword.
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
  • you can declare multiple constant or multiple variables on a single line, separated by commas.
    var x = 0.0, y = 0.0, z = 0.0
    note: if a stored value in your code won’t change, always declare it as a constant with the let keyword. Use variables only for storing values that need to be able to change.

type annotations

  • write type annotations when declaring constants or variables, to be clear the kind of value the constants or variables can store.
  • write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.
    var welcomeMessage : String
  • you can define multiple related variables of a same type on a single line, separated by commas, with a type annotation after the last variable name.
    var red, green, blue : String
    it’s rare to write type annotations in practice. if you provide an initial value at the point that is defined, swift can almost always infer the type to be used for the constant or variable.
    let friendlyWelcome = "hi!"

naming constants and variables

  • constants and variables can contain almost any character
    let π = 3.14159
    let 🐂 = "bull"
  • once you declare a constant or variable of a certain type, you can’t declare it again with the same name, or change it to store value of different type.
  • you cannot change a constant into a variable or a variable to constants.
  • you can change a value of an existing constant or variable to another value of compatible type.
var friendlyWelcome = "hello!"
friendlyWelcome = "fk u!"

printing constants and variables

  • you can print the current value of constants or variables with the print(_:separator:terminator:) function
    print(friendlyWelcome)
    • the separator and the terminator have default value
    • by default, the function terminates the line it prints by adding a line break.
    • to print a line without a line break, pass an empty string as the terminator
      print(someValue, terminator: "")
      #string interpolation
  • to prompt swift to replace the name of a constant or variable in a long string with the current value of constant or variable, wrap it in parentheses and escape it with backslash before opening parenthesis
    print("the current value of friendlyWelcome is \(friendlyWelcome)")

Integers

  • Integers are whole numbers with no fractional component, such as 42 or -11.
  • Integers are either signed or unsigned
  • swift provides signed and unsigned integers in 8, 16, 32, 64 bit forms.
    • a 8-bit unsigned integer is of type UInt8
    • a 32-bit signed integer is of type Int32

integer bounds

  • you can access maximum and minimum values of each integer type with its max and min properties
    let minValue = UInt8.min
    let maxValue = UInt8.max

Int

  • Int has the same size as the current platform’s native word size
    • on a 32-bit platform, Int is the same size as Int32
    • on a 64-bit platform, Int is the same size as Int64
  • unless you need to work with specific size of integer, always use Int for integer values in your code

UInt

  • UInt is an unsigned integer type
  • Uint has the same size as the current platform’s native word size
    note: use UInt only when you specifically need an unsigned integer type with the same size as the current platform’s native word size. if this isn’t the case, Int is preferred

Double

  • Double has a precision of at least 15 decimal digits
    #numeric literals
  • A decimal number, with no prefix
  • A binary number, with a 0b prefix
  • An octal number, with a 0o prefix
  • A hexadecimal number, with a 0x prefix
    #type aliases
  • type aliases define a name for an existing type
  • you can define type aliases with the typealias keyword
  • type aliases are useful when you want to refer to an existing type by a name that is more appropriate
    typealias AudioSample = UInt16
  • you can use the alias anywhere you might use the original name

tuples

  • tuple groups multiple values into a compound value
  • the value within a tuple can be of any type and they don’t have to be the same type
  • tuples can contain as many different types as you like
    let http404error = (404, "not found")
  • you can decompose a tuple into separated constants or variables
let (statusCode, statusMessage) = http404error
print(statusCode)
print(statusMessage)
  • if you only need some of the tuple’s value, ignore parts of the tuple with an underscore(_) when decompose the tuple
let (statusCode, _) = http404error
print(statusCode)
  • you can access the individual element value with the number index starting at 0
print(http404error.0)
print(http404error.1)
  • you can name the individual element value of a tuple when the tuple is defined
let http200status = (statusCode: 200, description: "OK")
  • if you name the element values in a tuple, you can use the names to access the values of elements
print(http200status.statusCode)
print(http200status.description)
  • tuples are useful as the return values of function. the function provides more useful information about its outcome than if it could only return a single value of a single type
    #optionals
  • you use optionals in situation where a value may be absent.
  • a optional value represents 2 possibilities
    • there is a value, and you can unwrap the optional and access the value
    • there isn’t a value at all
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)

nil

  • you can set an optional variable to a valueless state by assigning it the special value nil
var serverResponseCode: Int? = 404
serverResponseCode = nil

note: nil cannot be used with none-optional constants and variables

  • if you define an optional variable without default value, the variable is automatically set to nil
let surveyAnswer: String?

if statement and forced unwrapping

  • you can use a if statement to find out whether an optional contains a value, by comparing the optional against nil.
  • if an optional has a value, it is not equal to nil
     if convertedNumber != nil {
      print("convertedNumber contains a value")
    }
    
  • if you are sure the optional does contain a value, you can access its value by adding a exclamation point to the end of the optional’s name. this is known as forced unwrapping of the optional’s value
    if convertedNumber != nil {
      print("convertedNumber's value is \(convertedNumber!)")
    }
    

optional binding

  • you can use optional binding to find out whether an optional contains a value, and if it contains, make that value available as a temporary constant or variable.
if let/var constantName = someOptional {
  statements
}
if let actualNumber = Int(possibleNumber) {
  print("the string \(possibleNumber) has the integer value of \(actualNumber)")
} else {
  print("the string \(possibleNumber) cannot be converted to an integer")
}
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
    print("\(firstNumber) < \(secondNumber) < 100")
}
// Prints "4 < 42 < 100"

if let firstNumber = Int("4") {
    if let secondNumber = Int("42") {
        if firstNumber < secondNumber && secondNumber < 100 {
            print("\(firstNumber) < \(secondNumber) < 100")
        }
    }
}
// Prints "4 < 42 < 100"

implicitly unwrapped optionals

  • placing an exclamation pointer after the optional’s type when you declare it, rather than placing an exclamation pointer after the optional’s name when you use it
  • you can use an implicitly unwrapped optional without an exclamation pointer after the optional’s name
let possibleString: String? = "an normal optional"
let forcedString: String = possibleString!

let assumedString: String! = "an implicitly unwrapped optional"
let implicitString: String = assumedString
  • when you use an implicitly unwrapped optional, swift first tries to use it as an ordinary optional value. if it can’t be used as an ordinary optional value, swift forced unwrap the value.
let optionalString = assumedString
// the type of optionalString is "String?" and assumedString isn't force- unwrapped
  • if an implicitly unwrapped optional is nil and you try to access its value, you’ll trigger a runtime error.
  • you can check whether an implicitly unwrapped optional is nil the same way you check a normal optional
if assumedString != nil {
  print(assumedString)
}

if let definiteString = assumedString {
  print(definiteString)
}

note: don’t use implicitly unwrapped optionals when there’s a possibility of a variable becoming nil
#error handling

  • when a function encounter an error, it throws an error. that function’s caller can catch the error and respond appropriately
func canThrowAnError() throws { 
// this function may or may not throw an error
}
  • a function indicates that it can throw an error by including throws keyword in its declaration.
  • when you call a function that throws an error, you prepend try keyword to the expression
do {
  canThrowAnError()
  // no error was thrown
} catch {
  // an error was thrown
}
  • a do statement creates a new containing scope, which allows errors propagated to one or more catch clauses
func makeASandwich() {
   //...
}
do {
  try makeASandwich()
  eatASandwich()
} catch SandwichError.outOfCleanDishes {
  washDishes()
} catch SandwichError.missingIngredients {
  buyGroceries(ingredients)
}

assertions and preconditions

  • if the Boolean condition in the assertions or preconditions evaluate to true, code execution continues as usual.
  • if the condition evaluates to false, code execution ends and your app terminate.
  • use assertions and preconditions to express the assumptions you make and expectations you have while coding.
    • assertions help you find mistakes and incorrect assumptions during development
    • preconditions help you detect issues in production
  • difference between assertions and preconditions is when they are checked
    • assertions are checked only when debug builds
    • preconditions are checked in both debug and production builds
    • in production builds, the condition inside an assertion doesn’t evaluate, which means you can use as many assertions as you want during your development process, without impacting performance in production
  • assert(::file:line:)
let age = -1
assert(age >= 0, "a person's age cannot be less than 0")
  • and you can omit the assertion message
assert(age >= 0)
  • if the code already checks the condition, you can use assertionFailure(_:file:line:) function to indicate that an assertion has failed.
if age >= 10 {
//...
} else if age >= 0 {
//...
} else {
  assertionFailure("a person's age can't be less than 0")
}
  • you can write a precondition by precondition(::file:line:) function
precondition(index > 0, "index must be greater than 0")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值