ThE uSeFuL
ThE uSeFuL

Reputation: 1534

Error when passing an enum for code in NSError initializer

I'm trying setup some custom error codes for my app using enum. But I get an error when I called the NSError initializer. Below is the code I have so far,

enum FYIError : Int{
    case emptyData = 1
    case apiError = 2
}

class Test{
    func customErrorTest (){
       let customError:NSError = NSError(domain: "mydomain", code: FYIError.apiError, userInfo: Test.userInfo(""))
    }

    static private func userInfo (message:String) -> [NSObject: AnyObject]{

    var msg:String = message
    if (msg.characters.count<0){
        msg = "Oops! Something went wrong. Please try again later."
    }

    var dict = [NSObject: AnyObject]()
    dict[NSLocalizedDescriptionKey]        = msg
    dict[NSLocalizedFailureReasonErrorKey] = msg
    dict[NSUnderlyingErrorKey]             = msg

    return dict
}
}

The error I get is as follows,

enter image description here

Upvotes: 1

Views: 737

Answers (2)

Knight0fDragon
Knight0fDragon

Reputation: 16827

You are getting this because you need to use the rawValue of the enum:

let customError:NSError = NSError(domain: "mydomain", code: FYIError.apiError.rawValue, userInfo: Test.userInfo(""))

code needs type Int, using the specified enum will only get you a member of the enum type, the rawValue will get you the Int value if your specified enum

Upvotes: 2

Blake Lockley
Blake Lockley

Reputation: 2961

As the compiler error suggests you are trying to pass in an FYIError type as opposed to an Int. To get the raw value that you assigned to that enum case simply use the rawValue property as so:

let customError:NSError = NSError(domain: "mydomain", code: FYIError.apiError.rawValue, userInfo: Test.userInfo(""))

Upvotes: 3

Related Questions