* Closures
: ๋๋ค์ ๊ฐ์๊ณ .
: Closure๋ named Closure๊ณผ unnamed Closure๊ฐ ์๋ค. named Closure๊ฐ ์ผ๋ฐ swift ํจ์๋ฅผ ๋งํ๊ณ , unnamed Closure๋ ์ด๋ฆ์์ด ์ฌ์ฉํ๋ ํจ์๋ฅผ ๋งํ๋ค. ์ผ๋ฐ์ ์ผ๋ก Closure๋ผ๊ณ ํ๋ฉด unnamed Closure๋ฅผ ๋ปํ๋ค.
์๋ completionHandler๋ก ์ฌ์ฉํ handle ํจ์๋ฅผ ๋ณด์.
handle ํจ์๋ฅผ func ํจ์๋ก ๋ช ์ํ์ฌ ๋ฐ๋ก ์ ์ํด์ฃผ์๋ค. ์ด๋ฐ๊ฑธ named Closure๋ผ๊ณ ํ๋ค.
์ด๊ฑธ Closure(unnamed Closure)๋ก ๋ณ๊ฒฝํ๋ฉด ๋ค์๊ณผ ๊ฐ์ด ๋๋ค.
ํจ์๋ช ์ ์์ ๊ณ ์ธ์๋ง ๋จ๊ธด ํ, in ์์ handle ํจ์์ ์๋ ๋ด์ฉ์ ์ ์ด์คฌ๋ค.
์ด๋ ๊ฒ ํจ์๋ช ์์ด ์ธ์, ๋ฆฌํด, ํจ์๋ด์ฉ์ ์ง์ ์ ์ ์ ์๋ ๊ฒ์ Closure๋ผ๊ณ ํ๋ค.
๋๋ค์์ฒ๋ผ ์ฝ๋ ๊ฐ๊ฒฐ์ฑ์ ์ํด ์ฌ์ฉํ๋ฏ๋ก ์์์๋์.
* Closure ๊ธฐ๋ณธ ํํ
{(Parameters) -> Return Type in
//์คํ๊ตฌ๋ฌธ
}
* Clima ํ๋ก์ ํธ์ ์ ์ฉํ ์ ์ฒด ์ฝ๋
import Foundation
struct WeatherManager{
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=7722c26a2cee69ed24d77d3f57d3daf3&units=metric"
func fetchWeather(cityName: String){
let urlString = "\(weatherURL)&q=\(cityName)"
performRequest(urlString: urlString)
}
func performRequest(urlString: String){
//1. Create a URL
if let url = URL(string: urlString){
//2. Create a URLSession
let session = URLSession(configuration: .default)
//3. Give the session a task
let task = session.dataTask(with: url, completionHandler: handle(data : response: error: ))
//4. Start the task
task.resume()
}
}
func handle(data: Data?, response: URLResponse?, error: Error?){
if error != nil {
print(error!)
return
}
if let safeData = data {
let dataString = String(data: safeData, encoding: .utf8)
print(dataString)
}
}
}
performRequest ํจ์์ session.dataTask handler ๋ถ๋ถ์ Closure ํํ๋ก ๋ฐ๊ฟ๋ณด์.
import Foundation
struct WeatherManager{
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=7722c26a2cee69ed24d77d3f57d3daf3&units=metric"
func fetchWeather(cityName: String){
let urlString = "\(weatherURL)&q=\(cityName)"
performRequest(urlString: urlString)
}
func performRequest(urlString: String){
//1. Create a URL
if let url = URL(string: urlString){
//2. Create a URLSession
let session = URLSession(configuration: .default)
//3. Give the session a task
let task = session.dataTask(with: url){ (data, response, error) in
if error != nil {
print(error!)
return
}
if let safeData = data {
let dataString = String(data: safeData, encoding: .utf8)
print(dataString)
}
}
//4. Start the task
task.resume()
}
}
}
ํจ์ฌ ์ฝ๋๊ฐ ์งง์์ง๊ธด ํ๋๋ฐ, ๊ฐ๋ ์ฑ ์ธก๋ฉด์ ๊ณ ๋ คํด์ ์ํฉ์ ๋ง๊ฒ ์ฌ์ฉํด์ผ ํ ๊ฒ ๊ฐ๋ค.
'๐ฑ App Development Study > iOS๐' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Udemy iOS & Swift Bootcamp] Computed Property(์ฐ์ฐ ํ๋กํผํฐ) (0) | 2023.05.07 |
---|---|
[Udemy iOS & Swift Bootcamp] API ๋ก Json ๋ฐ์ดํฐ ๋ฐ์์ค๊ธฐ. Json Parsing (0) | 2023.05.06 |
[Udemy iOS & Swift Bootcamp] Delegate Design Pattern (0) | 2023.04.25 |
[Udemy iOS & Swift Bootcamp] UITextField, UITextFieldDelegate (0) | 2023.04.25 |
[Udemy iOS & Swift Bootcamp] Protocol (0) | 2023.04.10 |