jessesquires / jessesquires.com

Turing complete with a stack of 0xdeadbeef
https://www.jessesquires.com
Other
46 stars 19 forks source link

Improving multiplatform SwiftUI code #181

Closed ConfusedVorlon closed 1 year ago

ConfusedVorlon commented 1 year ago

Comments, Questions, Feedback: https://www.jessesquires.com/blog/2023/03/23/improve-multiplatform-swiftui-code/

I love your idea of giving Double a platform-specific initialiser, but I didn't want to repeat that for Double/Float/Int Also - I don't write for watchOS, so I created an init that will simply fatalError if I abuse it...

How about this:

extension Encodable {
    init(iOS: Self, watchOS: Self, macOS: Self, tvOS: Self) {
        #if os(iOS)
        self = iOS
        #elseif os(watchOS)
        self = watchOS
        #elseif os(tvOS)
        self = tvOS
        #elseif os(macOS)
        self = macOS
        #else
        fatalError()
        #endif
    }

    //Use this if you're not building for watchOS
    init(iOS: Self, macOS: Self) {
        #if os(iOS)
        self = iOS
        #elseif os(macOS)
        self = macOS
        #else
        fatalError()
        #endif
    }
}

I chose Encodable as it is about the most generic protocol I could think of. Most everyday types are Encodable...

jessesquires commented 1 year ago

Thanks for reading and sharing @ConfusedVorlon!

Yes, I kept the blog post simple. Depending on your needs you'll need to make adjustments.

I chose Encodable as it is about the most generic protocol I could think of.

Unfortunately, this doesn't really make sense for the majority of Encodable types.

I would recommend writing an extension on FloatingPoint or Numeric or any of the other numeric protocols instead.

github-actions[bot] commented 1 year ago

Thanks so much for leaving feedback about this blog post! After 2 weeks of inactivity these issues are automatically closed, but feel free to continue the discussion!