I'm a noobie in Swift. I would like to pass an instance of GameViewController or GameScene to a HelperClass as follows. In java I could use Object
for this. How is this done in Swift?
func getHighscores(leaderboardID: String, caller: **whatTypeHere**) {
...
}
so basically I want to notify the right caller when I get the highscores from the GameCenter.
A Java object is a member (also called an instance) of a Java class. Each object has an identity, a behavior and a state. The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created at runtime from templates, which are also known as classes.
Java Classes/Objects Java is an object-oriented programming language. Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.
As I understand you want "caller" to be any type you want. In this case you need to use "AnyObject" type here. Documentation
AnyObject is the type for "could be anything" in Swift. What you probably actually want is to define a Protocol that both GameViewController and GameScene implement:
protocol HighScoreReceiver {
func gotNewScores(scores:[Int])
}
class GameViewController: UIViewController, HighScoreReceiver {
func gotNewScores(scores: [Int]) {
// do something here
}
}
class GameScene: HighScoreReceiver {
func gotNewScores(scores: [Int]) {
// do something here
}
}
class Helper {
func getHighscores(leaderboardID: String, caller: HighScoreReceiver) {
//get the scores, then...
caller.gotNewScores(scores)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With