ObservedOptionalObject

0.1.1

Observe objects in SwiftUI Views which may be nil
fourplusone/observed-optional-object

What's New

2021-09-05T10:16:24Z
  • [FEAT] iOS Support

ObservedOptionalObject

Swift

Rationale

SwiftUIs @ObservedObject requires that the observed object actually exists. In some cases it's convenient to observe an object which might be nil. In this case, @ObservedOptionalObject can be used.

struct SomeView: View {
    // Instead of
    @ObservedObject var anObject: Model? // Won't work
    
    // use
    @ObservedOptionalObject var anObject: Model?
    
    var body: some View {
        HStack {
            Text("Name")
            if let name = anObject?.name {
                Text(name)
            }
        }
    }
}

Please note, that @ObservedOptionalObject is only useful if your contains content that should be displayed, even when the object is nil. Otherwise the view should be contained within an if let statement: if let obj = obj { SomeView(anObject: obj) }

Installation

This package is available via SwiftPM

dependencies: [
    .package(url: "https://github.com/fourplusone/observed-optional-object.git", 
        .upToNextMinor(from: "0.1.0")
    )
]

License

This project is licensed under the MIT License.

Description

  • Swift Tools 5.3.0
View More Packages from this Author

Dependencies

  • None
Last updated: Wed Nov 06 2024 08:47:11 GMT-1000 (Hawaii-Aleutian Standard Time)