Swift Basic

1 minute read

1. Swift Collection Data Structure

Array

  • Initialization
  var arr = [Int]()
  var arr2 : [Int] = []
  var arr3 : Array<Int> = []
 
  • Get size
let n = arr.count
  • Access
arr[arr.startIndex]
arr.first

arr[arr.endIndex-1]
arr.last
  • Append/Insert
  arr.append("something")
  arr.insert("something insert", at:1)
  
  • Remove/Pop/Drop
arr.removeFirst()

arr.popLast()
arr.removeLast()

arr.remove(at:3)

arr.removeAll()

let getArrExceptFirst = arr.dropFirst()
let getArrExceptLast = arr.dropLast()
  • Modify
arr[1] = "Test"
arr[0..1] = ["First", "Second"]
arr[0..1] = ["First", "Second", "Third"]
  • Sort/Sorted
arr.sort()
arr.sort(by: >)

let sortedArr = arr.sorted(by:<)
let sortedArrDescending = arr.sorted(by:>)
  • Min/Max
arr.min()
arr.max()
  • Reverse
arr.reverse()

String/Character

  • Access String’s Character
let str = "Swift String Test"
str[str.startIndex]
str[str.index(before: endIndex)]
str[str.index(str.startIndex, offsetBy: 4)]
str[str.index(str.endIndex, offsetBy: -2)]
  • Append a Character to a String
    • Convert a Character to a String
var newStr = str + [aCharacter]
  • Using insert()
str.insert(m[i] ?? "-", at: str.endIndex)

Dictionary

  • Initialization
var dic = [Integer: String]()
  • Sort
let sortedByKey = dic.keys.sorted(by:<)
let sortedByVal = dic.values.sorted(by:<)
let sortedByAll = dic.sorted(by:<)

: The two above return an Array. So, if you want to access the values of sortedByKey, try this

for key in sortedByKey {
  print(dic[key])
}

2. Control Flow

For

  for i in arr {}
  for i in 0...n {}
  for i in 0..<n {}
  for i in (0...n).reversed() {}
  for i in (0..<n>).reversed() {}
  for i in stride(from: n, to: 0, by: -2) {}
  

3. Operator

Unsupported Operator

  • ++, --
someInt++       //Not working

someInt += 1
  • &&
if someInt>0 && someInt<10 {} //Not working

if someInt>0, someInt<10 {}

4. Optional

Converting Optional

  • Optional Binding
var something: String? = "Hello!"
if let val = something {
  print("This is not nill.")
}
  • Optional Chaining (+ Optional Binding)
var dic = [Integer: someClass]
if let val = dic[keyValue]?.someProperty {
  print("This is not nil.")
}
  • Forced Unwrapping
    This is usually used when class initialization or implicitly unwrapped optionals.
var button: UIButton!
  • Nil-Coalescing Operator
let intLet = 10 + somethingOptional ?? 0

Referece

Comments