forked from swiftwasm/JavaScriptKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSUndefinedOr.swift
More file actions
56 lines (50 loc) · 1.77 KB
/
JSUndefinedOr.swift
File metadata and controls
56 lines (50 loc) · 1.77 KB
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
46
47
48
49
50
51
52
53
54
55
56
/// A wrapper that represents a JavaScript value of `Wrapped | undefined`.
///
/// In BridgeJS, `Optional<Wrapped>` is bridged as `Wrapped | null`.
/// Use `JSUndefinedOr<Wrapped>` when the JavaScript API expects
/// `Wrapped | undefined` instead.
@frozen public enum JSUndefinedOr<Wrapped> {
/// The JavaScript value is `undefined`.
case undefined
/// The JavaScript value is present and wrapped.
case value(Wrapped)
/// Creates a wrapper from a Swift optional.
///
/// - Parameter optional: The optional value to wrap.
/// `nil` becomes ``undefined`` and a non-`nil` value becomes ``value(_:)``.
@inlinable
public init(optional: Wrapped?) {
self = optional.map(Self.value) ?? .undefined
}
/// Returns the wrapped value as a Swift optional.
///
/// Returns `nil` when this value is ``undefined``.
@inlinable
public var asOptional: Wrapped? {
switch self {
case .undefined:
return nil
case .value(let wrapped):
return wrapped
}
}
}
extension JSUndefinedOr: ConstructibleFromJSValue where Wrapped: ConstructibleFromJSValue {
public static func construct(from value: JSValue) -> Self? {
if value.isUndefined { return .undefined }
guard let wrapped = Wrapped.construct(from: value) else { return nil }
return .value(wrapped)
}
}
extension JSUndefinedOr: ConvertibleToJSValue where Wrapped: ConvertibleToJSValue {
public var jsValue: JSValue {
switch self {
case .undefined:
return .undefined
case .value(let wrapped):
return wrapped.jsValue
}
}
}
// MARK: - BridgeJS (via _BridgedAsOptional in BridgeJSIntrinsics)
@_spi(BridgeJS) extension JSUndefinedOr: _BridgedAsOptional {}