2
import UIKit
import Combine

class ViewController: UIViewController {

    @IBOutlet weak var allowMessageSwitch: UISwitch!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var messageLabel: UILabel!

    @Published var canSendMessages: Bool = false
    @Published var newMsg: String = ""

    private var switchSubscriber: AnyCancellable?
    private var btnSubscriber: AnyCancellable?


    override func viewDidLoad() {
        allowMessageSwitch.isOn = false
        super.viewDidLoad()
        setupProcesscingChain()
    }

    func setupProcesscingChain() {
        switchSubscriber = $canSendMessages.receive(on: DispatchQueue.main).assign(to: \.isEnabled, on: sendButton)

        btnSubscriber = $newMsg.receive(on: DispatchQueue.main).assign(to: \.text, on: messageLabel)
    }

    @IBAction func didSwitch (_ sender: UISwitch) {
        canSendMessages = sender.isOn
    }

    @IBAction func sendMessage( _ sender: Any) {
    }


}

I am getting error in

btnSubscriber = $newMsg.receive(on: DispatchQueue.main).assign(to: \.text, on: messageLabel)

error msg is

Type of expression is ambiguous without more context

I dont understand why label does not work as Switcher (bool)

I assume it is because \.isEnabled is not optional, and \.text is optional..??

how can I make this work with the same format. this is for practice and to understand how Combine works.. please help!

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Kyo Heo
  • 141
  • 8
  • 1
    Very nice use of Published. (Could have used setter observer instead in this situation.) – matt Feb 26 '20 at 04:01

1 Answers1

4
lableSubscriber = $newMsg.receive(on: DispatchQueue.main).assign(to: \.text!, on: messageLabel)

I solved it on my own! it was very simple. just force unwrap the keyPath.

Kyo Heo
  • 141
  • 8
  • Not ideal solution. Better to map to an Optional. See https://stackoverflow.com/questions/59637100/how-does-swift-referencewritablekeypath-work-with-an-optional-property – matt Feb 26 '20 at 04:07