새로 알아간 것들
Debug
assert
import Foundation
func test(i: Int) {
assert(i != 0, "오마이갓")
}
print(test(i: 0))
print("Hello")
git
git add -u
String
replacingOccurrences - 값 변경
var str = "hohoho"
print(str.replacingOccurrences(of: "o", with: "a"))
Array
swapAt - 위치 변경
var name = ["paul", "John", "Hong"]
name.swapAt(0, 1)
print(name)
Combination
func combos<T>(elements: ArraySlice<T>, k: Int) -> [[T]] {
if k == 0 {
return [[]]
}
guard let first = elements.first else {
return []
}
let head = [first]
let subcombos = combos(elements: elements, k: k - 1)
var ret = subcombos.map { head + $0 }
ret += combos(elements: elements.dropFirst(), k: k)
return ret
}
func combos<T>(elements: Array<T>, k: Int) -> [[T]] {
return combos(elements: ArraySlice(elements), k: k)
}
let numbers = [1,2,3,4,5]
print(combos(elements:numbers,k:2))
Number of Combination
func combinations(_ n: Int, choose k: Int) -> Int {
return permutations(n, k) / factorial(k)
}
combinations(28, choose: 5)
Permutation
func permuteWirth<T>(_ a: [T], _ n: Int) {
if n == 0 {
print(a)
} else {
var a = a
permuteWirth(a, n - 1)
for i in 0..<n {
a.swapAt(i, n)
permuteWirth(a, n - 1)
a.swapAt(i, n)
}
}
}
let letters = ["a", "b", "c"]
permuteWirth(letters, letters.count - 1)
forEach
numbers.forEach {
print($0)
}
클로저를 리턴하는 함수
- 선언했던 함수는 그 안의 변수 값이 바뀌지 않는다
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementer() -> Int {
runningTotal += amount
return runningTotal
}
return incrementer
}
let incrementByTen = makeIncrementer(forIncrement: 10)
print(incrementByTen())
print(incrementByTen())
let incrementBy7 = makeIncrementer(forIncrement: 7)
print(incrementBy7())
print(incrementByTen())
동기와 비동기
https://usinuniverse.bitbucket.io/blog/syncasync.html