[Swift] 非同期処理の並行処理

async / awaitの組み合わせで非同期処理を行う

ContentView.swift

func getWho() async -> String {
    await Task.sleep(5 * 1000 * 1000 * 1000)
    return "山本さん"
}

func getMessage() async -> String {
    await Task.sleep(3 * 1000 * 1000 * 1000)
    return "ハロー"
}

class StopWatch: ObservableObject {
    
    @Published var elapsedTime: Double = 0.0
    private var timer = Timer()
    
    func start() {
        guard !timer.isValid else { return }
        self.elapsedTime = 0.0
        timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true) {
            _ in
            self.elapsedTime += 0.01
        }
    }
    
    func stop() {
        timer.invalidate()
    }
}

struct ContentView: View {
    
    @State var message:String = ""
    @ObservedObject var watch = StopWatch()
    
    var body: some View {
        VStack {
            Button(action: {
                Task {
                    watch.start()
                    message = "_ _ _"
                    
                    async let who = getWho()
                    async let msg = getMessage()
                    message = await who + "," + msg + " ! "
                    watch.stop()
                }
            }) {
                Label("async TEST", systemImage: "testtube.2")
                    .background(
                        Capsule()
                            .stroke(lineWidth: 1)
                            .frame(width: 180, height: 40)
                    )
            }.padding(30)
            Text("\(message)").font(.title2)
            let milliSeconds = Int((watch.elapsedTime) * 100)%100
            let seconds = Int(watch.elapsedTime)
            Text("\(seconds).\(milliSeconds)").padding()
            Spacer()
        }
    }
}

OK, もう一声