Why do we need NoOp types?

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?

  1. 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).
  2. 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.
  3. There could be historical reasons too, for example in Java it’s tricky to deal with NullPointerException so NoOps 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!

Asked on August 31, 2020 in iOS,   Swift.
Add Comment
1 Answer(s)

It is the "Null object pattern", https://en.wikipedia.org/wiki/Null_object_pattern

Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.