Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Java Object in Swift?

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.

like image 622
user594883 Avatar asked Jun 23 '16 04:06

user594883


People also ask

What is an alternative name for an object in Java?

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.

What is object in Java with example?

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.


2 Answers

As I understand you want "caller" to be any type you want. In this case you need to use "AnyObject" type here. Documentation

like image 82
Petr Lazarev Avatar answered Oct 14 '22 22:10

Petr Lazarev


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)
    }
}
like image 28
Mark Bessey Avatar answered Oct 14 '22 21:10

Mark Bessey