luisgmnz
luisgmnz

Reputation: 19

How can I change a value inside a class from an outside function?

How can I change the value inside a class from an outside function?

class MyClass {
   var number = 5
}

func changeNumber(){
   number = 2
}

I'm more or less new to delegate and protocols, but as I understand it always happens between two classes. My problem is that that function runs when a certain note is played on a midi device and I need to change the text value of a label in a viewControler class.

Upvotes: 1

Views: 466

Answers (2)

Luca Sfragara
Luca Sfragara

Reputation: 634

welcome to StackOverflow! You could just change the numberProperty like this

class MyClass{
    var number = 5
}

func changeNumber(_ myClass: MyClass){
    myClass.number = 2
}

let myClassInstance = MyClass()
print(myClassInstance.number) //5

changeNumber(myClassInstance)
print(myClassInstance.number) //2

Upvotes: 1

Daniel T.
Daniel T.

Reputation: 33979

The conventional approach is to make the view controller the delegate:

final class MyViewController: UIViewController { 
    var number = 5
    let midi = Midi()
    func viewDidLoad() { 
        super.viewDidLoad()
        midi.delegate = self
    }
}

extension MyViewController: MidiDelegate { 
    func changeNumber(device: Midi, value: Int) { 
        number = value
    }
}

Upvotes: 0

Related Questions