swiftuiwatchoswatchos-6version-compatibility

How to deal with Swift UI version compatible to support older devices?


I'm developing an apple watch app on Xcode 12 beta WatchOS 7.

I intend to support watchOS 6 too.

Following code has error and I don't know how to deal with it, it belongs to SwiftUI problem:

struct CompactStockListView: View {
  var body: some View {
    NavigationView {
      List(getStocks(), id: \.id) { stock in
        CompactStockRowView(stock: stock)
          .padding(.vertical, 6)
      }
      .navigationBarTitle(Text("Landmarks"))
    }
  }
}

Xcode notice the error:

'NavigationView' is only available in application extensions for watchOS 7.0 or newer

Next step: Trying this solutions without success:

struct CompactStockListView: View {
  var body: some View {
    getListSafe() // Error
  }
  
  func getListSafe() -> View {  // Error tooo
    if #available(watchOSApplicationExtension 7.0, *) {
      return NavigationView {
        List(getStocks(), id: \.id) { stock in
          CompactStockRowView(stock: stock)
            .padding(.vertical, 6)
        }
        .navigationBarTitle(Text("Landmarks"))
      }
    } else {
      // Fallback on earlier versions
      return List(getStocks(), id: \.id) { stock in
        CompactStockRowView(stock: stock)
          .padding(.vertical, 6)
      }
    }
  }
}

Solution

  • Try the following

      @ViewBuilder
      func getListSafe() -> some View {
        if #available(watchOSApplicationExtension 7.0, *) {
          NavigationView {
            List(getStocks(), id: \.id) { stock in
              CompactStockRowView(stock: stock)
                .padding(.vertical, 6)
            }
            .navigationBarTitle(Text("Landmarks"))
          }
        } else {
          // Fallback on earlier versions
          List(getStocks(), id: \.id) { stock in
            CompactStockRowView(stock: stock)
              .padding(.vertical, 6)
          }
        }
      }