https://github.com/JeaSungLEE/iOSInterviewquestions
with perplexity
Swift의 에러 처리 방법에 대해 설명해주세요.
throws, try, catch 키워드의 사용 방법은 무엇인가요?
enum NetworkError: Error { case invalidURL case noResponse } func fetchData(from url: String) throws -> String { guard url.starts(with: "https://") else { throw NetworkError.invalidURL } return "Data from \(url)" }
let data = try fetchData(from: "https://example.com")
do { let data = try fetchData(from: "invalid-url") print(data) } catch NetworkError.invalidURL { print("잘못된 URL입니다.") } catch { print("예상치 못한 에러: \(error)") }
옵셔널을 사용한 에러 처리와 do-catch를 사용하는 에러 처리의 차이는 무엇인가요?
try?를 사용하면 에러가 발생할 경우 결과를 nil로 반환.let result = try? fetchData(from: "invalid-url") print(result) // nil
do-catch는 에러의 종류·내용을 확인하고 구체적으로 대응할 수 있음.do { let data = try fetchData(from: "invalid-url") print(data) } catch { print("에러 발생! \(error)") }
에러를 전파하는 방법은 무엇인가요?
func processData() throws { try fetchData(from: "invalid-url") } do { try processData() } catch { print("Error: \(error)") }
func perform(operation: () throws -> Void) rethrows { try operation() } try perform { throw NetworkError.noResponse }