
Model
struct Person {let name, birthDate} 이런 느낌.View
Controller
함수의 파라미터로 전달이 가능하거나 함수에서 리턴이 가능하거나 변수나 상수에 저장 및 할당이 가능함
*// closureSample* 상수에 **할당
**let** closureSample = { (city: String) -> String **in**
"I'm in \(city)"
}
*//* 할당된 **클로저 **실행
closureSample("서울")
*//* 상수에 **클로저 **할당
**let** sayHello = { (name: String) -> String **in**
"Hello \(name)"
}
*//* 상수에 **클로저 **할당
**let** sayGoodbye = { (name: String) -> String **in**
"Goodbye \(name)"
}
*//* 함수의 **파라미터로 **클로저를 **전달받도록 **정의
**func** **greet**(**name**: String, **sayWhat**: (String) -> String) {
sayWhat(name)
}
*//* 함수 **파라미터로 **클로저 **전달
*//* 리턴값 *: Hello* 이름
greet(name: "Jaebin", sayWhat: sayHello)
*//* 함수 **파라미터로 **클로저 **전달
*//* 리턴값 *: Goodbye* 이름
greet(name: "Jaebin", sayWhat: sayGoodbye)
*//* 상수 **클로저를 **전달하지 **않고 **직접 **클로저를 **구현해 **전달 **가능
greet(name: "Jaebin", sayWhat: {( displayName: String) -> String **in**
"How are you \(displayName)?"
})
*//* 함수의 **리턴값으로 **클로저 **반환
**func** **saySomething**(**word**: String) -> (String) -> String {
**return** { (word) -> String **in**
"I said \(word)"
}
}
*//* 리턴된 **클로저를 **상수에 **할당
**let** say = saySomething("Hello")
*//* 클로저 **호출
*//* 리턴값 *: I said Hello*
say()
func fetchData(completion: @escaping (Data?, Error?) -> Void) {
// 네트워크 요청 수행
// 요청이 완료되면 completion 클로저 호출
}
fetchData { data, error in
if let data = data {
print("Data received: \(data)")
} else if let error = error {
print("Error: \(error)")
}
}
2.상태 캡쳐
func makeIncrementer(incrementAmount: Int) -> () -> Int {
var total = 0
let incrementer: () -> Int = {
total += incrementAmount
return total
}
return incrementer
}
let incrementByTwo = makeIncrementer(incrementAmount: 2)
print(incrementByTwo()) // 2
print(incrementByTwo()) // 4
3.고차함수
let numbers = [1, 2, 3, 4, 5]
let evenNumbers = numbers.filter { $0 % 2 == 0 }
print(evenNumbers) // [2, 4]
let add: (Int, Int) -> Int = { $0 + $1 }
let subtract: (Int, Int) -> Int = { $0 - $1 }
print(add(3, 4)) // 7
print(subtract(10, 5)) // 5
ARC(Automatic reference Counting)를 이용해서 데이터 관리. 객체는 참조가 더 이상 필요하지 않할 때 자동으로 메모리 해체
클로저 같은 구조에서는 강한 참조가 순환 참조를 일으킬 수 잇음 → 두 개 이상의 객체가 서로를 강하게 참조하여 서로가 메모리에서 해체되지 않음 → 메모리 누수
override func viewDidload(){
let url = "..."
let apiURI : URL! = URL(string:url) // URl 변환
let apidata = try ! Data(contentOf:apiURI)
let log = NSString(data: apidata, encoding: String.Encoding.utf8.rawValue) ?? ""
NSLog("Api result = \(log)")
}
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowArbitraryLoads</key>
<true/>
</dict>
overrid func viewDidload(){
...
do{
//jsonObject -> NSDictionary // jsonArray -> NSArray
let apiDictionary =
try JSONSerialization.jsonObject(with: apidata,options:[]) as! NSDictionary //options : 파싱 옵션 (없어서 공란)
let hoppin = apiDictionary["hoppin"] as! NSDictionary
let movies = hoppin["movies"] as! NSDictionary
let movie = movies["movie"] as! NSArray
for row in movie {
let r = row as! NSDictionary
let mvo = MovieVO()
mvo.title = r["title"] as? String
mvo.description = r["description"] as? String
mvo.thumbnailImage = r["thumbnailImage"] as? String
mvo.detail = r["linkUrl"] as? String
mvo.rating = ((r["ratingAverage"] as? NSString).doubleValue)
self.list.append(mvo)
}
}.catch { }
}