Skip to content

Instantly share code, notes, and snippets.

@hcrub
Last active May 3, 2019 21:28
Show Gist options
  • Save hcrub/e2aabc7959bb5c7c1b35ba8acd9e5f2a to your computer and use it in GitHub Desktop.
Save hcrub/e2aabc7959bb5c7c1b35ba8acd9e5f2a to your computer and use it in GitHub Desktop.
Interface for determining and scoping optional Associated Types
/// Interface representing an optionally nil value type.
protocol OptionalType: ExpressibleByNilLiteral {
/// The boxed optional type.
associatedtype Wrapped
}
extension Optional: OptionalType {}
// Example
// In this case, we have an extension that returns an optional type.
// If the associated type is defined as optional, you will return a double optional.
// The following example shows how you can use the `OptionalType` interface to scope
// an extension containing an associated type defined as optional. E.g. `InputType??`
protocol Validation {
associatedType InputType
}
// Returns `InputType?`
extension Validation {
func validate() -> InputType? {}
}
// Returns `InputType?`
extension Validation: InputType {
func validate() -> InputType {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment