Raj
Raj

Reputation: 61

passing integer Argument in a function

func getDriverFromId(var id : Int?) -> String {

    if id == nil {
        return "No Driver Assigned"
    }
    else {
        loadDriversREST()
    }

    return "test"

}

getDriverFromId(nil)

I am getting an error "getDriverFromID with an argument list of type (nil)"

Upvotes: 0

Views: 3671

Answers (2)

Jon
Jon

Reputation: 41

Your code is actually correct and works fine. That said I have a couple of suggestions and have included a (working) playground for you.

Given that your code first checks whether the ID is nil, you don't actually need the else as the flow would stop (or return) anyway - this makes it a little more pleasing to the eye...

With this in mind, your function would look like this:

func getDriverFromId(var id : Int?) -> String {

    if id == nil {
        return "No Driver Assigned"
    }

    loadDriversREST()

    return "test"

}

Also, unless you plan on changing "id" from within the code of the function, then you don't need var before it. Basically, function arguments are non-mutable by default so you can't change them, adding var enables you to change the value of the argument within the code.

With all of this in mind, here is a playground showing everything working. Hope this helped...

import UIKit

func loadDriversREST() {
    // doesn't actually do anything
    return
}

func getDriverFromId(id : Int?) -> String {

    if id == nil {
        return "No Driver Assigned"
    }


    loadDriversREST()

    return "test"

}

println(getDriverFromId(nil))   // this works
println(getDriverFromId(15))    // this works

Upvotes: 1

Fred Faust
Fred Faust

Reputation: 6790

enter image description here

func getDriveFromId(var id: Int?) -> String {

if id == nil {

    return "No Driver Assigned"

} else {

    //Your func
    return "test"
}

}

Upvotes: 0

Related Questions