swift中java接口或Objective c协议的等价物是什么? [英] What is the equivalent for java interfaces or objective c protocols in swift?

查看:129
本文介绍了swift中java接口或Objective c协议的等价物是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找新的Swift语言,尝试在互联网上浏览并在提供的书中搜索后,找到Swift中的接口(在java中)或协议(在objective-c中)的等价物。通过Apple,我似乎无法找到它。

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中这个组件的名称是什么,它的语法是什么?

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

推荐答案

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

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
}

符合协议有点不同:

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.")
      }
}

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

这篇关于swift中java接口或Objective c协议的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆