Preprocessor to support different platforms

in order to support on linux and certain apple's platforms(os), I need to write duplicated code like below.
Does it have a better solution? like preprocessor that I can restrict to the certain os?

extension Collection {
    #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
    @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
    @discardableResult
    func parallel<T: Sendable,U: Sendable>(transform: @Sendable @escaping (T) async throws -> U) async rethrows -> [U] where T == Element {
        let newArr = try await withThrowingTaskGroup(of: U.self, returning: [U].self) { taskGroup in
            self.forEach { elm in
                taskGroup.addTask { try await transform(elm) }
            }

            return try await taskGroup.reduce(into: [U]()) { partialResult, name in
                 partialResult.append(name)
            }
        }
        return newArr
    }
    #elseif os(Linux)
    @discardableResult
    func parallel<T: Sendable,U: Sendable>(transform: @Sendable @escaping (T) async throws -> U) async rethrows -> [U] where T == Element {
        let newArr = try await withThrowingTaskGroup(of: U.self, returning: [U].self) { taskGroup in
            self.forEach { elm in
                taskGroup.addTask { try await transform(elm) }
            }

            return try await taskGroup.reduce(into: [U]()) { partialResult, name in
                 partialResult.append(name)
            }
        }
        return newArr
    }
    #endif
}

The * in @available means “and everywhere else”. As far as I can tell your other code is identical, so you should be able to just drop the condition altogether. But maybe I missed a subtle difference?

4 Likes

Thanks. you are right. I didn't know * means everywhere else that including the os like linux or windows.

1 Like