Created
February 21, 2018 06:39
-
-
Save klundberg/30f8565737ad70a3114ef351e19334f3 to your computer and use it in GitHub Desktop.
Conditional conformance in swift 4.1 for optional for some common protocols
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: ??? | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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