swift 문법 총정리(12) Generic & higher order function

Updated:

Generic

var intValue: Int = 5
var doubleValue: Double = 5.6
var floatValue: Float = 3.4
func plus(a: Int, b: Int) -> Int{
	return a + b
	}

func plusGeneric<T: Numeric>(a:T, b:T) -> T {
	return a+b
}

var result = plusGeneric(a: doubleValue, b: doubleValue)
result
//11.2

Higher Order Function

//map
var numberArray = [2, 3, 6, 4, 1]
let mapped = numberArray.map{$0 * 10}
print(mapped)
//[20,30,60,40,10]

let stringArray = ["lee", "june", "kim"]
let mappedString = stringArray.map{ $0.uppercased()}
print(mappedString)



//compact map
let someArray = [2, 3, 4, "kim", "jin"]
let compactMapped = someArray.compactMap{ $0 as? Int }
//2,3,4 int 형만 출력
//map과의 차이점은 map은 optional 상태로 출력된다.



//filter
let over3 = numberArray.filter{ $0 > 3}
print(over3)
//6,4



//reduce
numberArray.reduce(0) { (value1, value2) -> Int in
	return value1 + value2
}
//16

//위의 내용을 생략하고 아래와같이 쓸 수 있다.
let reduceResult = numberArray.reduce(0) {$0 + $1}
print(reduceResult)


let reduceResultString = stringArray.reduce("", {$0 + $1})
print(redueceResultString)
//leejunekim



// sort
numberArray.sort()
//오름차순으로 정렬
numberArray.sort(by: >)
//내림차순으로 정렬

let sorted = numberArray.sorted()
//sorted는 return type이 있고 sort는 return type이 없다. 즉 sorted는 변경된 값이 적용되지 않고 새로운
값에 넣어준다.
//즉 원래 array에 영향을 주지 않는다.

Reference

인프런 강의

Tags: ,

Categories:

Updated:

Leave a comment