1

I would like to create a protocol that has different activities. my reference is an interface on Java Android that we can able create a variable as an interface then we initialize like we implement in class. so, what the equivalent of the interface on swift code?


//Android Interface
private OnValueChanged joinDay, birthDay;

//initialize
joinDay = new OnValueChanged(value -> {
//somecode
});

birthday = new OnValueChanged(value -> {
//somecode
});


interface OnValueChanged{
   void didChanged(Date value)
}

//END OF ANDROID INTERFACE








//SWIFT PROTOCOL

class myClass : OnValueChanged{


func didChanged(Int value){
//somecode
}

}

protocol OnValueChanged{
    func didChanged(Int value)
}

//END OF SWIFT PROTOCOL

What I want is to create a variable or something like that, which could implement different codes for the same Class like on Android Side.

how to do that in swift?

thanks

1

1 Answer 1

0

You don't need a separate type for this in Swift. Your Java interface can be represented with a closure in Swift. Specifically, it is a closure of type (Int) -> Void.

You can declare joinDay and birthday like this in Swift:

var joinDay: ((Int) -> Void)?
var birthday: ((Int) -> Void)?

To assign an "implementation", do:

joinDay = { value in
    // do something with the parameter "value"
    print(value)
}

And the equivalent of calling joinDay.didChanged(someValue) in Swift would be:

joinDay?(someValue)

For more info on how to use closures, see Closures in the Swift Guide.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.