일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- EventLoop
- WWDC24
- SwiftUI
- URLSession
- dart
- Architecture
- 문법
- isolate
- designpattern
- swift
- GIT
- LifeCycle
- tuist
- SampleApp
- dartz
- dgcharts
- weatherkit
- flutter
- uikit
- philipshue
- OpenAI
- AppleDeveloper
- Xcode
- chartsorg
- iot
- WebSocket
- network
- raspberrypi5
- embedded-swift
- builder
Archives
- Today
- Total
Jaebi의 Binary는 호남선
Swift - 문법 (Protocols and Extensions, Error Handling, Generics) 본문
목차 Open
Protocols and Extensions
- protocol (interface) →
protocol
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
- classes, enumerations, and structures can all adopt protocols
- modify structure →
mutating
- modify structure →
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
- add functionality to an existing type →
extension
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
Error Handling
- represent errors →
Error
protocol
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}
- throw an error →
throw
, mark a function that can throw an error →throws
func send(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
return "Job sent"
}
- Error handling #1 →
do-catch
- mark code that can throw an error →
try
- mark code that can throw an error →
do {
let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
print(printerResponse)
} catch PrinterError.onFire {
print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
print("Printer error: \(printerError).")
} catch {
print(error)
}
- Error handling #2 →
try?
- convert result to an optional, if throws an error result is nil
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
Generics
- name inside angle brackets to make generic function or type →
<Int>
- specify list of requirements →
where
- Writing
<T: Equatable>
is the same as writing<T> ... where T: Equatable
Reference
Documentation
docs.swift.org
'Swift' 카테고리의 다른 글
WeatherKit 사용 (WWDC 2024) (1) | 2024.06.13 |
---|---|
Swift - 문법 (Property Wrappers) (0) | 2024.06.12 |
Swift - 문법 (Object and Classes, Enumerations and Structures, Concurrency) (0) | 2024.06.12 |
Swift - 문법 (Values, Control Flow, Functions and Closures) (0) | 2024.06.11 |
Philips Hue 연동 프로젝트 (0) | 2024.06.08 |