Note: This is not a Swift-only question, it's related in every language with Optional
type.
I see some Swift projects doing that: var foo: Foo = NoOpFoo()
AFAIK this basically means "this foo does nothing" and can be also expressed as var foo: Foo? = nil
I'm wondering what can be the reason(s) behind NoOp
-instead-of-Optional
decision?
- I can think of performance first:
Optional
seems to add a few more lines to assembly output (but I'm not really convinced with that). - The reason could be boilerplate of unwrapping optionals as well: but most of the examples I've seen are types that don't even return values, therefore call sites don't need to unwrap neither.
- There could be historical reasons too, for example in Java it's tricky to deal with
NullPointerException
soNoOp
s may come handy... but in Swift?
Here is an example from swift-log project:
public struct Logger {
var handler: LogHandler
internal init(_ handler: LogHandler) {
self.handler = handler
}
}
public struct SwiftLogNoOpLogHandler: LogHandler { ... }
Logger
is designed to work with a LogHandler
; to my understanding if you pass NoOpHandler
to your Logger
then you should probably turn your yourLogger: Logger
into myLogger: Logger? = nil
Real-world use cases and/or your personal experiences would be much appreciated!
Aucun commentaire:
Enregistrer un commentaire