-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtryOptional.swift
45 lines (37 loc) · 1.16 KB
/
tryOptional.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//
// tryOptional.swift
//
// Created by German Velibekov on 06/02/2020.
// Copyright © 2020 German Velibekov. All rights reserved.
//
import Foundation
public struct NilError<T>: Error, CustomStringConvertible {
private let _description: String
init(optional: Optional<T>) {
_description = "Nil returned for optional of type: \(T.self)"
}
init(optional: Optional<T>, file: String, line: Int) {
_description = "Nil returned for optional of type: \(T.self) at \(file) line: \(line)"
}
public var description: String {
return _description
}
}
prefix operator ??
public extension Optional {
func unwrap(file: String = #file,
line: Int = #line) throws -> Wrapped {
guard let unwrapped = self else {
throw NilError(optional: self,
file: file,
line: line)
}
return unwrapped
}
static prefix func ?? (optional: Optional) throws -> Wrapped {
guard let unwrapped = optional else {
throw NilError(optional: optional)
}
return unwrapped
}
}