ios swift中java接口或objective c协议的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24071525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:34:19  来源:igfitidea点击:

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

iosmacosinterfaceprotocolsswift

提问by Martin Cazares

I've been looking in to the new Swift language trying to find what's the equivalent for an interface(in java) or a protocol(in objective-c) in Swift, after surfing on the internet and searching in the book provided by Apple, I still can't seem to find it.

我一直在寻找新的 Swift 语言,试图在 Swift 中找到接口(在 Java 中)或协议(在 Objective-c 中)的等价物,在互联网上冲浪并在 Apple 提供的书中搜索之后,我似乎仍然无法找到它。

Does any one know what's the name of this component in swift and what's its syntax?

有谁知道swift中这个组件的名称是什么,它的语法是什么?

回答by cdstamper

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

Swift中的协议与 Objc 非常相似,除了您不仅可以在类上使用它们之外,还可以在结构体和枚举上使用它们。

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.

注意:默认实现必须通过扩展添加,而不是在协议定义本身中 - 协议不是一个具体的对象,所以它实际上不能附加方法主体。将默认实现视为 C 样式模板;本质上,编译器复制声明并将其粘贴到每个遵守协议的对象中。

回答by Lorenzo Boccaccia

swift has protocols as well, hereis the relevant documentation:

swift 也有协议,这里是相关的文档: