Swift Function call list incorrect parameter type

2019-02-26 11:45发布

问题:

I define the below list swift class, and try to call the sfAuthenticateUser from the viewcontroller. But the Xcode intellisense list the wrong parameter type other than the type i defined.

ERROR : Cannot convert value of type 'String' to expected argument type 'APISFAuthentication'

Xcode Version 7.1 (7B91b)

//View Controller method call as below

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

// Class Definition as below

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;
    }
}

Please refer to the screen shot

回答1:

The problem is that you try to call an instance function without having an actual instance at hand.

You either have to create an instance and call the method on that instance:

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

or define the function as a class function:

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

Explanation:

What Xcode offers you and what confuses you is the class offers the capability to get a reference to some of its instance functions by passing an instance to it:

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

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

k now is the function bla. You can now call k via k() etc.