Swiftpack.co -  Misoservices/MisoViewOptional as Swift Package
Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
Misoservices/MisoViewOptional
SwiftUI package to allow for conditional compilation of modifiers
.package(url: "https://github.com/Misoservices/MisoViewOptional.git", from: "1.0.0")

MisoViewOptional

SwiftUI package to allow for conditional compilation of modifiers

This is the simplest Swift package ever. It's mostly a design pattern to allow for an optional modifier that returns an AnyView.

Why?

When you compile something conditionally, sometimes, a modifier is not available in a platform. For example, macOS doesn't support navigationBarItems, and you cannot simply do

VStack {
   Spacer()
}
#if !os(macOS)
.navigationBarItems(...)
#endif

Also, the usual pattern of setting someting to nil doesn't actually work.

There are also some other uses, especially when some modifiers don't support a nil default. You can if its usage completely away through the .optional modifier.

Why AnyView?

Not only is this not hurting the performance, but also, due to Swift's lack of preprocessor, the #if is actually defined as a command. And because the #else is undefined, the system cannot determine what should be the return type. There might be a better design pattern, and please don't hesitate to provide a better implementation.

Usage

import MisoViewOptional

VStack {
    Spacer()
}
.frame(width: 123, height: 456)
.optional() { content in
    #if os(macOS)
    return AnyView(content)
    #else
    return AnyView(content.navigationBarTitle("MyTitle")
                          .navigationBarItems(trailing: doneButton))
    #endif
}

Colophon

The official address for this package

The git / package url

This package is created and maintained by Misoservices Inc. and is licensed under the BSL-1.0: Boost Software License - Version 1.0.

GitHub

link
Stars: 5
Last commit: 5 days ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Release Notes

Initial release
1 year ago

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API