如何在Swift中创建一个接口

Jay*_*ngh 6 protocols interface ios swift

我想在swift中创建类似接口的功能,我的目标是当我调用另一个类时假设我正在调用API并且该类的响应我想反映到我当前的屏幕,在android界面中用来实现但应该是什么我在swift中使用它?任何人都可以帮我举个例子.android的代码如下:

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) {
    }
}
Run Code Online (Sandbox Code Playgroud)

Sur*_*put 10

而不是接口swift有协议.

协议定义了适合特定任务或功能的方法,属性和其他要求的蓝图.然后,可以通过类,结构或枚举来采用该协议,以提供这些要求的实际实现.任何满足协议要求的类型都被认为符合该协议.

我们参加考试.

protocol Animal {
    func canSwim() -> Bool
}
Run Code Online (Sandbox Code Playgroud)

我们有一个类确认这个协议名称Animal

class Human : Animal {
   func canSwim() -> Bool {
     return true
   }
}
Run Code Online (Sandbox Code Playgroud)

更多信息请访问 - https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html


Jay*_*eep 6

您正在寻找“协议”。接口与 Swift 中的协议相同。

protocol Shape {
    func shapeName() -> String
}

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

class Triangle: Shape {
    func shapeName() -> String {
        return "triangle"
    }
}
Run Code Online (Sandbox Code Playgroud)

class并且struct两者都可以实现protocol.