Skip to content

Instantly share code, notes, and snippets.

@tgnivekucn
Created August 22, 2018 13:30
Show Gist options
  • Save tgnivekucn/79ad108c2eeb29c05cf6ec3a304ca81a to your computer and use it in GitHub Desktop.
Save tgnivekucn/79ad108c2eeb29c05cf6ec3a304ca81a to your computer and use it in GitHub Desktop.
//用語言提供的基本語法找出陣列中的奇數和偶數
func test1(arr: [Int]) -> Void {
for item in arr {
if isOdd(val: item) {
print("\(item)")
}
}
}
func test2(arr: [Int]) -> Void {
for item in arr {
if isEven(val: item) {
print("\(item)")
}
}
}
func isOdd(val: Int) -> Bool {
return val % 2 != 0
}
func isEven(val: Int) -> Bool {
return val % 2 == 0
}
let a = [1,2,3,4]
test1(arr: a)
test2(arr: a)
//使用closure:
func test(arr: [Int], closure: (_ val: Int) -> Bool) -> Void {
for item in arr {
if closure(item) {
print("\(item)")
}
}
}
let isOdd = { $0%2 == 1} //note:isOdd就像是語言提供的基本語法,讓我們找出array中的數字是否為奇數
let isEven = { $0%2 == 0} //note:isEven就像是語言提供的基本語法,讓我們找出array中的數字是否偶數
test(arr: a, closure: isOdd)
test(arr: a, closure: isEven)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment