-
Some time ago I noticed that in some situations we initialise clients and in others we use them as computed properties, can someone explain to me when we should choose one solution over the other? Computed property approach: static var liveValue: SpeechClient {
let speech = Speech()
return SpeechClient(
authorizationStatus: { SFSpeechRecognizer.authorizationStatus() },
requestAuthorization: {
await withUnsafeContinuation { continuation in
SFSpeechRecognizer.requestAuthorization { status in
continuation.resume(returning: status)
}
}
},
startTask: { request in
await speech.startTask(request: request)
}
)
} Initialising approach: static let liveValue = DataManager(
load: { url in try Data(contentsOf: url) },
save: { data, url in try data.write(to: url) }
) So far, I created all my clients as computed properties, but I ran into problems where my client started to be initialized more than once. How should we do it? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi @Namedix, dependencies should be cached the first time they are accessed. Can you provide a demonstration of a dependency being initialized multiple times? |
Beta Was this translation helpful? Give feedback.
Hi @Namedix, good to hear, and we also discuss that gotcha in the docs.
Both styles are fine to use and are legitimate. But sometimes only the computed static property style is possible because you need to capture some state on the inside, like in the
SpeechClient
. But if you don't need to capture that state, then astatic let
is just fine. Or if you prefer to coalesce on a single style for consistency, then feel free to usestatic var
all the time.