Skip to content

Instantly share code, notes, and snippets.

@AppleCEO
AppleCEO / Planet.swift
Created May 22, 2019 07:39
rawValue example
enum Planet: Int {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
enum CompassPoint: String {
case north, south, east, west
}
// function
func backward(_ s1: String, _ s2: String) -> Bool {
return s1 > s2
}
// closure
{ (_ s1: String, _ s2: String) -> Bool in
return s1 > s2
}
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let namesSorted1 = names.sorted(by: { (_ s1: String, _ s2: String) -> Bool in
return s1 > s2
})
let namesSorted2 = names.sorted(by: { (_ s1: String, _ s2: String) -> Bool in
s1 > s2
})
let namesSorted3 = names.sorted(by: { (s1, s2) -> Bool in s1 > s2 })
let namesSorted4 = names.sorted(by: { (_ s1: String, _ s2: String) in s1 > s2 })
let numbers = [20, 19, 7, 12]
let threeTimesNumbers = numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
// [60, 57, 21, 36]
let numbers = [20, 19, 7, 12]
var threeTimesNumbers = [Int]()
for number in numbers {
threeTimesNumbers.append(number*3)
}
// [60, 57, 21, 36]
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let strings = numbers.map { (number) -> String in
var number = number
var output = ""
repeat {
let scores = [10, 80, 95, 100, 92]
let hasPassedExam = scores.filter({ (score: Int) -> Bool in
return score > 80
})
// [95, 100, 92]
let scores = [90, 58, 36, 82]
let hasPassedExam = scores.map({ (score: Int) -> String in
if score > 80 { return "합격" }
return "불합격"
})
// ["합격", "불합격", "불합격", "합격"]