swift - 如何遵守 Swift 中的协议(protocol)?

标签 swift

<分区>

我尝试将 facebookSDK 方法转换为 swift 代码:

- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
                        user:`(id<FBGraphUser>)user {}

问题在于:

id<FBGraphUser>)user

最佳答案

<>在 Objective-C 中:符合协议(protocol)

<>在 Swift 中用于泛型


如果只想符合用户的类型是id并且符合FBGraphUser协议(protocol):

id 是 Swift 中的 AnyObject。

您可以在变量名称的声明中使用协议(protocol)作为类型。

func loginViewFetchedUserInfo<T where T: AnyObject, T: FBGraphUser>(loginView: FBLoginView, #user: T)
{
   ...
}
// use the # only if you want the call of the method to write 'user:'

使用方法:

那就更简单了。首先你需要有方法的对象,我们称它为facebookObject .现在,如果你有一个变量 myUser类型为 AnyObject, FBGraphUser .还有一个变量 myLoginView类型 FBLoginView .然后你用

调用方法
facebookObject.loginViewFetchedUserInfo(loginView: myLoginView, user: myLoginView)

可能是 user:不需要,因为这是方法的正常模式。


然而,您可以使用 where 做更多事情关键词

Use where after the type name to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.

摘自:Apple Inc.“The Swift Programming Language”。 iBooks .

关于swift - 如何遵守 Swift 中的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24158390/

相关文章:

swift - 在 WatchOS 上的 SwiftUI 应用程序中是否可以进行基于页面的导航?

ios - 如何将 userdefault 值转换为 URL?

arrays - 快速保持数组顺序,同时填充它

ios - 转换为 swift 3.0 时,UIButton 上 'dismiss()' 的使用不明确

ios - 从 'CLLocation?' 向下转换为 'CLLocation' 仅解开可选值;您的意思是使用 '!' 吗?

ios - 如果应用程序进入后台,如何阻止其刷新?

swift playgrounds 显示 uiview 不间断循环

ios - 滑动返回只能在屏幕边缘使用吗?

Swift:二叉树搜索,int 不在树中

ios - 使用 WKWebView 时自定义状态栏颜色