Compare Protocol in Swift VS Interface in Java

Compare Protocol in Swift vs Interface in Java

Essentially protocols are very similar to Java interfaces except for:

  • Swift protocols can also specify properties that must be implemented (i.e. fields)
  • Swift protocols need to deal with value/reference through the use of the mutating keyword (because protocols can be implemented by structures, enumerations or classes).
  • you can combine protocols at any point using "Protocol Composition". This replaces the older swift protocol<A, B> way of protocol composition. For example, declaring a function parameter that must adhere to protocol Named and Aged as:
    func wishHappyBirthday(to celebrator: Named & Aged) {}

These are the immediately apparent differences for a Java developer (or at least what I've spotted so far). There's more info here.

What is the equivalent for java interfaces or objective c protocols in swift?

Protocols in Swift are very similar to Objc, except you may use them not only on classes, but also on structs and enums.

protocol SomeProtocol {
var fullName: String { get } // You can require iVars
class func someTypeMethod() // ...or class methods
}

Conforming to a protocol is a bit different:

class myClass: NSObject, SomeProtocol // Specify protocol(s) after the class type

You can also extend a protocol with a default (overridable) function implementation:

extension SomeProtocol {
// Provide a default implementation:
class func someTypeMethod() {
print("This implementation will be added to objects that adhere to SomeProtocol, at compile time")
print("...unless the object overrides this default implementation.")
}
}

Note: default implementations must be added via extension, and not in the protocol definition itself - a protocol is not a concrete object, so it can't actually have method bodies attached. Think of a default implementation as a C-style template; essentially the compiler copies the declaration and pastes it into each object which adheres to the protocol.

What is the difference between a protocol and a interface in Objective-c?

a protocol in Objective-C is the same as an interface in java, if thats what you mean

Java interface equivalent in Swift

The Swift equivalent to an interface is a Protocol, as Connor says in his answer.

Again, borrowing from Connor's answer:

protocol MyEngine {
func doWork() -> Bool
}

You can't instantiate objects of type MyEngine directly. Instead you need to define one or more objects that conform to the protocol:

class Obj1: MyEngine {
func doWork() -> Bool {
print("in Obj1 doWork()")
return true
}
}

class Obj2: MyEngine {
func doWork() -> Bool {
print("in Obj2 doWork()")
return true
}
}

You can then define an array of objects that conform to the protocol:

var objArray = [MyEngine]()

Then populate the array:

objArray.append(Obj1())
objArray.append(Obj2())
objArray.append(Obj2())
objArray.append(Obj1())

You can then say

objArray.forEach{$0.doWork()}

How can I use Swift protocol function like as Android interface listener implement?

You have to set delegate in your viewcontroller and implement protocol methods in your viewcontroller

class MyVC : UIViewController, OnButtonListener {
override func viewDidLoad() {
super.viewDidLoad()
let myView1 = MyView()
myView1. onButtonListener = self
let myView2 = MyView()
myView2. onButtonListener = self

}

func onButton1( _ val1: String ) {
print(val1)
}

func onButton2( _ val2: String ) {
print(val2)
}

}

**Method 2: ** You can use block as well

class MyView: UIView { 
var buttonAction : ((_ value : String) -> Void)? = nil
//.... your code

@objc func onB1() {
if let action = buttonAction {
action("abc")
}
}

@objc func onB2() {
if let action = buttonAction {
action("xyz")
}
}

}

In you ViewController

  override func viewDidLoad() {
super.viewDidLoad()
let myView1 = MyView()
myView1.buttonAction = { value in
print(value)
}
}

Protocol vs Interface

Objective C protocols serve basically the same purpose as interfaces in Java/ C#. Objective C interface files are different. Like C, Objective C has interface files that publicly declare the methods and properties of a class, that are then implemented in an implementation file. For example you may have an interface file of a class that looks something like this:

@interface  
-(void)myMethod;
@end

then in your implementation file you actually implement the method:

-(void)myMethod{
//code
}

Swift does away with separate interface and implementation files. So it only has protocols.

What is the Difference Between Classes vs Protocols

A class serves as a blueprint for creating one or more objects based on specific implementation of that class.
A good analogy is a form for cutting out butter-cookies. The form‘s attributes (shape, size, height) define the cookies that you can cut out with it. You have only one form (class) but you can create many cookies (instances of that class, ie. objects) with it. All cookies are based on that particular form.
Similarily all objects that are instances of that class are identical in their attributes.

Classes = data and methods (special functions), all sophistically bundled together.

Classes define, what their inner content (data) is + what kind of work (methods) they can do.
The content is based on variables that hold various number types, strings, constants, and other more sophisiticated content + methods which are chunks of code that (when executed) perform some computational operations with various data.

All methods defined in class have their
Definition - that defines the name of the method + what (if any) data the methods takes in for processing and what (if any) data the methods spits out for processing by someone else. All methods defined in class also have Implementation – the actual code that provides the processing – it is the innerworkings of methods.. inside there is code that processes the data and also that is able to ask other methods for subprocessing data. So the class is a very noble type in programming.

If you understand the above, you will understand what a protocol is.

A protocol is a set of one or more method declarations and that set has a name and represents a protocol. I say declarations, because the methods that together are defined by a particular protocol, do not have any implementation code defined.. The only thing that exist is their names declared.
Look above - in class, you have always defined not only what methods the class has, but also how that work will be done. But methods in protocol do not have any implementation.

Lets have a real life analogy again, it helps. If you come to my house to live here for a week, you will need to adhere to my TidyUp protocol. The TidyUp protocol defines three methods - wash the dishes every day, clean the room, and ventilate fresh air. These three methods, I define them..are something you will do. But I absolutely do not care, how the implementation should look like, I just nominaly define the methods. You will implement them, ie.you define how the details of that work (those methods) will look like. I just say, adhere to my protocol and implement it as you see fit.

Finale – You can declare some class. You can separately also declare a protocol. And you can then declare, that this class, in addition to its own methods, will adopt or adhere to that protocol, ie. the class wil implement the protocol’s methods.



Related Topics



Leave a reply



Submit