ios - Swift 函数调用列表不正确的参数类型

标签 ios swift swift2 xcode7

我定义了下面的列表 swift 类,并尝试从 viewcontroller 调用 sfAuthenticateUser。但是 Xcode intellisense 列出了错误的参数类型,而不是我定义的类型。

错误:无法将“字符串”类型的值转换为预期的参数类型“APISFAuthentication”

Xcode 版本 7.1 (7B91b)

//View Controller方法调用如下

@IBAction func ActionNext(sender: AnyObject) {
    let sss =  APISFAuthentication.sfAuthenticateUser(<#T##APISFAuthentication#>)
}

//类定义如下

class APISFAuthentication {
    init(x: Float, y: Float) {            
    }

    func sfAuthenticateUser(userEmail: String) -> Bool {
        let manager = AFHTTPRequestOperationManager()
        let postData = ["grant_type":"password","client_id":APISessionInfo.SF_CLIENT_ID,"client_secret":APISessionInfo.SF_CLIENT_SECRET,"username":APISessionInfo.SF_GUEST_USER,"password":APISessionInfo.SF_GUEST_USER_PASSWORD]

        manager.POST(APISessionInfo.SF_APP_URL,
            parameters: postData,
            success: { (operation, responseObject) in
                print("JSON: " + responseObject.description)
            },
            failure: { (operation, error) in
                print("Error: " + error.localizedDescription)

        })
        return true;
    }
}

请引用屏幕截图 enter image description here

最佳答案

问题是您在没有实际实例的情况下尝试调用实例函数。

您要么必须创建一个实例并在该实例上调用该方法:

let instance = APISFAuthentication(...)
instance. sfAuthenticateUser(...)

或者将函数定义为类函数:

class func sfAuthenticateUser(userEmail: String) -> Bool {
    ...
}

解释:

Xcode 为您提供的和让您感到困惑的是,该类提供了通过向其传递实例来获取对其某些实例函数的引用的能力:

class ABC {
    func bla() -> String {
        return ""
    }
}

let instance = ABC()
let k = ABC.bla(instance) // k is of type () -> String

k 现在函数bla。您现在可以通过 k() 等调用 k

关于ios - Swift 函数调用列表不正确的参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34907598/

相关文章:

swift2 - 从 Int 列中获取最大值的最佳和最有效的方法是什么?

ios - swift 2 尝试/捕捉

ios - RestKit:在后台执行 RKMapperOperation 时崩溃

ios - 从 SpriteKit 中的类播放音频

objective-c - 搜索模板 tvOS

ios - UI更新太快怎么办?

ios - 创建嵌套 TableView 或单独的页面?

ios - CGDataProvider 在 Swift 4 中返回 null

ios - 是否可以为 iOS 创建自定义崩溃动画?

variables - 如何在 Swift 2 中保护现有变量赋值而不使用 let/var