Effectful read-only properties
About 3 min
Effectful read-only properties 관련
HACKING WITH SWIFT
What's new in Swift?
Effectful read-only properties | Changes in Swift 5.5
Effectful read-only properties
Available from Swift 5.5
SE-0310 (apple/swift-evolution
) upgrades Swift’s read-only properties to support the async
and throws
keywords, either individually or together, making them significantly more flexible.
To demonstrate this, we could create a BundleFile
struct that attempts to load the contents of a file in our app’s resource bundle. Because the file might not be there, might be there but can’t be read for some reason, or might be readable but so big it takes time to read, we could mark the contents
property as async throws
like this:
import Foundation
enum FileError: Error {
case missing, unreadable
}
struct BundleFile {
let filename: String
var contents: String {
get async throws {
guard let url = Bundle.main.url(forResource: filename, withExtension: nil) else {
throw FileError.missing
}
do {
return try String(contentsOf: url)
} catch {
throw FileError.unreadable
}
}
}
}
Because contents
is both async and throwing, we must use try await
when trying to read it:
func printHighScores() async throws {
let file = BundleFile(filename: "highscores")
try await print(file.contents)
}
Other Changes in Swift 5.5
Async await | Changes in Swift 5.5
Async await
Async sequences | Changes in Swift 5.5
Async sequences
Structured concurrency | Changes in Swift 5.5
Structured concurrency
async let bindings | Changes in Swift 5.5
async let bindings
Continuations for interfacing async tasks with synchronous code | Changes in Swift 5.5
Continuations for interfacing async tasks with synchronous code
Actors | Changes in Swift 5.5
Actors
Global actors | Changes in Swift 5.5
Global actors
Sendable and @Sendable closures | Changes in Swift 5.5
Sendable and @Sendable closures
if for postfix member expressions | Changes in Swift 5.5
if for postfix member expressions
Interchangeable use of CGFloat and Double types | Changes in Swift 5.5
Interchangeable use of CGFloat and Double types
Codable synthesis for enums with associated values | Changes in Swift 5.5
Codable synthesis for enums with associated values
lazy now works in local contexts | Changes in Swift 5.5
lazy now works in local contexts
Extending property wrappers to function and closure parameters | Changes in Swift 5.5
Extending property wrappers to function and closure parameters
Extending static member lookup in generic contexts | Changes in Swift 5.5
Extending static member lookup in generic contexts