How to create an interface in Swift

女生的网名这么多〃 提交于 2019-12-23 09:14:56

问题


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) {
    }
}

回答1:


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




回答2:


What are you finding is `Protocol'. Interfaces are same as protocol 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.



来源:https://stackoverflow.com/questions/45974041/how-to-create-an-interface-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!