Skip to content

Instantly share code, notes, and snippets.

@klundberg
Created February 21, 2018 06:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klundberg/30f8565737ad70a3114ef351e19334f3 to your computer and use it in GitHub Desktop.
Save klundberg/30f8565737ad70a3114ef351e19334f3 to your computer and use it in GitHub Desktop.
Conditional conformance in swift 4.1 for optional for some common protocols
extension Optional: Collection where Wrapped: Collection {
public typealias Element = Wrapped.Element
public typealias Index = Wrapped.Index
public func index(after i: Wrapped.Index) -> Wrapped.Index {
switch self {
case let value?:
return value.index(after: i)
case nil:
fatalError() // TODO: ???
}
}
public subscript(position: Wrapped.Index) -> Wrapped.Element {
switch self {
case let value?:
return value[position]
case nil:
preconditionFailure("Fatal error: Index out of range")
}
}
public var startIndex: Wrapped.Index {
switch self {
case let value?:
return value.startIndex
case nil:
fatalError() // TODO: ???
}
}
public var endIndex: Wrapped.Index {
switch self {
case let value?:
return value.endIndex
case nil:
fatalError() // TODO: ???
}
}
}
extension Optional: Sequence where Wrapped: Sequence {
public typealias Element = Wrapped.Element
public typealias Iterator = AnyIterator<Element>
public func makeIterator() -> AnyIterator<Wrapped.Element> {
switch self {
case let value?: return AnyIterator(value.makeIterator())
case nil: return AnyIterator({ return nil })
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment