We can create a SwiftUI app in Xcode, that targets multiple platforms (iOS, macOS, watchOS, etc.) using the same codebase. When you create an app, you can choose Multiplatform:

You will get this starter template:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
}
}
#Preview {
ContentView()
}
Where we will see a text view and an image view. You can run this app on both iOS and macOS. You can change the running destination from topbar:

We can run the app on both iOS and macOS. If you want to run the app on watchOS or another platform, you have to create a separate target. You can follow this article to add the watchOS platform to your existing SwiftUI project: Add the watchOS target to the existing iOS project.
For better preview in macOS, you can add frame modifier to VStack.
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
SwiftUI provides platform-specific views and modifiers that allow you to customize the experience for different platforms. Here’s an example of how to structure a basic multi-platform app and use conditional views based on the platform:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
#if os(iOS)
Text("iOS specific view")
.font(.title)
Button(action: {
print("iOS Button pressed")
}) {
Text("iOS Button")
.padding()
}
#elseif os(macOS)
Text("macOS specific view")
.font(.title)
Button(action: {
print("macOS Button pressed")
}) {
Text("macOS Button")
.padding()
}
#else
Text("Unsupported platform")
#endif
}
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
#Preview {
ContentView()
}
For example, we will get this output if we run the app on macOS:

And we will get this output if we run on iOS:

We used conditional like #if ... #endif. The condition is called a compile-time conditional directive in Swift. It is part of conditional compilation, which allows you to include or exclude parts of your code depending on the platform or configuration the code is being compiled for.
While simple views like Text or Button work across platforms, certain views, modifiers, or frameworks are platform-specific. In those cases, we use conditional compilation to include or exclude code for a specific platform. If you are new to SwiftUI, you can learn about it from this link.