28

i want to create functionality like interface in swift, my goal is when i call another class suppose i'm calling API and the response of that class i want to reflect in to my current screen, in android interface is used to achieve but what should i use in swift for that? can anyone help me with example. the code for android is given below...

public class ExecuteServerReq {
    public GetResponse getResponse = null;

    public void somemethod() {
        getResponse.onResponse(Response);
    } 
    public interface GetResponse {
        void onResponse(String objects);
    }
}


ExecuteServerReq executeServerReq = new ExecuteServerReq();

executeServerReq.getResponse = new ExecuteServerReq.GetResponse() {
    @Override
    public void onResponse(String objects) {
    }
}
7
  • in swift protocol works as interface.Google protocol in swift. Commented Aug 31, 2017 at 5:52
  • You can create protocol for achieve same Commented Aug 31, 2017 at 5:53
  • @TusharSharma any give me example .. Commented Aug 31, 2017 at 5:54
  • @MikeAlter how.... any example ??? Commented Aug 31, 2017 at 5:55
  • @Jaypraksh Sing countless tutorials and solutions on stack are already present please google . Commented Aug 31, 2017 at 5:56

2 Answers 2

41

Instead of interface swift have Protocols.

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements. Any type that satisfies the requirements of a protocol is said to conform to that protocol.

lets take an exam .

protocol Animal {
    func canSwim() -> Bool
}

and we have a class that confirm this protocol name Animal

class Human : Animal {
   func canSwim() -> Bool {
     return true
   }
}

for more go to - https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html

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

Comments

8

You are looking for `Protocols'. Interfaces are the same as protocols in Swift.

protocol Shape {
    func shapeName() -> String
}

class Circle: Shape {
    func shapeName() -> String {
        return "circle"
    }
  
}

class Triangle: Shape {
    func shapeName() -> String {
        return "triangle"
    }
}

class and struct both can implements the protocol.

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.