quanguyen
quanguyen

Reputation: 1463

Swift 2.0 - pass a tuple struct to function

I want to pass a struct of tuples to a function, and I got the error of unknown tuple fields:

import UIKit

struct MyClassConstants {
    static let DOMAIN = "MyClassDomain"

    struct Error {
        static let ERROR1 = (code: -1, description: "Error1 description")
        static let ERROR2 = (code: -2, description: "Error2 description")
    }
}

extension NSError {
    public class func MyClassError(error: MyClassConstants.Error) -> NSError {
        return NSError(domain: MyClassConstants.DOMAIN, code: error.code, userInfo: ["description": error.description]) // error here!!
    }
}

class MyClass: NSObject {
    // some properties
    func doSomething() {
       let error = NSError.MyClassError(MyClassConstants.Error.Error1)
       // ...
    }
}

The error is:

Value of type "MyClassConstants.Error" has no member 'code'.

I think the reason of the error in MyClassError is I have not casted error parameter to a tuple? How can I do that? Or any other reasons?

Thanks.

Upvotes: 1

Views: 100

Answers (1)

Sweeper
Sweeper

Reputation: 271625

It actually took me a while to figure out where the error is.

It's so easy to miss it.

The error occurs because the parameter - error is an instance of MyClassConstants.Error. Using this instance, you can only access instance methods or properties of that type. However, your MyClassConstants.Error has no instance properties! It contains only static properties!

You need to know that ERROR1 and ERROR2 are not of type MyClassConstants.Error. They are of type (code: Int, description: String)!

So yeah...

The second error that you get is at:

let error = NSError.MyClassError(MyClassConstants.Error.Error1)

Because ERROR1 is not of type MyClassConstants.Error, it cannot be passed into the method.

How to fix this:

Well, here's the self-explanatory code:

// Change MyClassError method to this:
public class func MyClassError(error: (code: Int, description: String)) -> NSError {
    return NSError(domain: MyClassConstants.DOMAIN, code: error.code, userInfo: ["description": error.description]) // error here!!
}

Upvotes: 3

Related Questions