<分区>
我尝试将 facebookSDK 方法转换为 swift 代码:
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:`(id<FBGraphUser>)user {}
问题在于:
id<FBGraphUser>)user
标签 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/