⛔️ escaping closure captures mutating 'self' parameter

🚧 施工中

👉 StackOverflow:What's 'Escaping closure captures mutating 'self' parameter' and how to fix it

import Combine
import SwiftUI
import PlaygroundSupport

let url: URL = "https://source.unsplash.com/random"    // 🌀URL

// performs a network request to fetch a random image from Unsplash’s public API
func imagePub() -> AnyPublisher<Image?, Never> {
    URLSession.shared
        .dataTaskPublisher(for: url)
        .map { data, _ in Image(uiImage: UIImage(data: data)!)}
        .print("image")
        .replaceError(with: nil)
        .eraseToAnyPublisher()
}

struct ContentView: View {
    
    @State private var image: Image? = nil
    
    // simulate user taps on a button
    let taps = PassthroughSubject<Void, Never>()
    
    var subscriptions = Set<AnyCancellable>()
    
    init() {
        taps
            // ⭐️ map the tap to a new network request
            // ⭐️ Publisher<Void, Never> --> Publisher<Publisher<Image?, Never>, Never>
            //    — a publisher of publishers
            .map { _ in imagePub() }
            
            // ⭐️ accept only the latest tap
            .switchToLatest()
            
            // ❌ escaping closure captures mutating `self` parameter
            .sink { self.image = $0 }
            
            // ❌ 雖然下面的語法沒有出現錯誤訊息,但依然沒用
            // .assign(to: \.image, on: self)
            
            .store(in: &subscriptions)
    }
    
    var body: some View {
        VStack {
            image
            Button(action: {
                self.taps.send()
            }, label: {
                Text("Tap").padding().background(Color.pink).cornerRadius(12)
            })
        }.padding().background(Color.gray)
    }
}

PlaygroundPage.current.setLiveView(ContentView())

Last updated