[SOLVED] Function should return String but returns (Function)

Issue

After creating an extension for an enum, I experience something odd.

I want to return a String based on the enum case, but instead I get Optional((Function))

Here is a snippet

enum ComparisonOperator: String, CaseIterable {
    case equalTo = "equal to"
    case greaterThan = "greater than"
    case greaterThanOrEqualTo = "greater than or equal to"
    case lessThan = "less than"
    case lessThanOrEqualTo = "less than or equal to"
    case differentFrom = "different from"
}

extension ComparisonOperator {
    func shortName() -> String {
        
        switch self {
            case .equalTo:
                return "equalTo"
            case .greaterThan:
                return "greaterThan"
            case .greaterThanOrEqualTo:
                return "greaterThanOrEqualTo"
            case .lessThan:
                return "lessThan"
            case .lessThanOrEqualTo:
                return "lessThanOrEqualTo"
            case .differentFrom:
                return "differentFrom"
        }
    }
}

I expect this to return the string value when calling the shortName() after a ComparisonOperator but instead I get the response above.

The test snippet:

let comparisonOperator = ComparisonOperator.greaterThanOrEqualTo
print(comparisonOperator.shortName)

Expected response:

greaterThanOrEqualTo

Actual response:

Optional((Function))

What am I doing wrong? 🙂

Solution

I suspect that where your problem is actually occurring, you’re calling comparisonOperator.shortName (resulting in an un-evaluated function), which is different from comparisonOperator.shortName()

Answered By – Alexander

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.