diff --git a/Sources/OpenSwiftUICore/Util/StandardLibraryAdditions.swift b/Sources/OpenSwiftUICore/Util/StandardLibraryAdditions.swift index b37101b9b..18e30b4d0 100644 --- a/Sources/OpenSwiftUICore/Util/StandardLibraryAdditions.swift +++ b/Sources/OpenSwiftUICore/Util/StandardLibraryAdditions.swift @@ -458,9 +458,17 @@ package enum IndirectOptional: ExpressibleByNilLiteral { } package var wrappedValue: Wrapped? { - switch self { - case .none: nil - case let .some(wrapped): wrapped + get { + switch self { + case .none: nil + case .some(let wrapped): wrapped + } + } + set { + switch newValue { + case .none: self = .none + case .some(let wrapped): self = .some(wrapped) + } } } } diff --git a/Tests/OpenSwiftUICoreTests/Util/StandardLibraryAdditionsTests.swift b/Tests/OpenSwiftUICoreTests/Util/StandardLibraryAdditionsTests.swift index fda4d4fef..7f519d485 100644 --- a/Tests/OpenSwiftUICoreTests/Util/StandardLibraryAdditionsTests.swift +++ b/Tests/OpenSwiftUICoreTests/Util/StandardLibraryAdditionsTests.swift @@ -618,3 +618,89 @@ struct BidirectionalCollectionInsertionSortTests { #expect(array == [.value(4), .invalid, .value(5), .value(2), .value(1)]) } } + +// MARK: - IndirectOptionalTests + +struct IndirectOptionalTests { + @Test + func initWithValue() { + let opt = IndirectOptional(42) + #expect(opt.wrappedValue == 42) + } + + @Test + func initWithNilLiteral() { + let opt: IndirectOptional = nil + #expect(opt.wrappedValue == nil) + } + + @Test + func initWithWrappedValue() { + let opt = IndirectOptional(wrappedValue: "hello") + #expect(opt.wrappedValue == "hello") + + let nilOpt = IndirectOptional(wrappedValue: nil) + #expect(nilOpt.wrappedValue == nil) + } + + @Test + func wrappedValueGetter() { + let some: IndirectOptional = .some(10) + let none: IndirectOptional = .none + + #expect(some.wrappedValue == 10) + #expect(none.wrappedValue == nil) + } + + @Test + func wrappedValueSetter() { + var opt: IndirectOptional = .none + + opt.wrappedValue = 42 + #expect(opt.wrappedValue == 42) + + opt.wrappedValue = 99 + #expect(opt.wrappedValue == 99) + + opt.wrappedValue = nil + #expect(opt.wrappedValue == nil) + } + + @Test + func wrappedValueSetterFromSomeToNone() { + var opt: IndirectOptional = .some("initial") + #expect(opt.wrappedValue == "initial") + + opt.wrappedValue = nil + #expect(opt.wrappedValue == nil) + } + + @Test + func wrappedValueSetterFromNoneToSome() { + var opt: IndirectOptional = .none + #expect(opt.wrappedValue == nil) + + opt.wrappedValue = "assigned" + #expect(opt.wrappedValue == "assigned") + } + + @Test + func equatable() { + let a: IndirectOptional = .some(5) + let b: IndirectOptional = .some(5) + let c: IndirectOptional = .some(10) + let d: IndirectOptional = .none + + #expect(a == b) + #expect(a != c) + #expect(a != d) + #expect(d == IndirectOptional.none) + } + + @Test + func hashable() { + let a: IndirectOptional = .some(5) + let b: IndirectOptional = .some(5) + #expect(a.hashValue == b.hashValue) + } +}