1

I have a function that should return String or Array:

func someFunc(isList:Bool=false) -> AnyObject {
        if isList {
            var results:[AnyObject] = [11, "123", [], "22"]
            return results
        } else {
            var result = "123"
            return result
        }
    }

But compiler says:

Return expression of type '[AnyObject]' does not conform to 'AnyObject'

6
  • why not just always return an array, but when your isList is false, return an array with only a string in it? Or why not just make the return variable optional and return nil in some cases, as it doesn't look like you're actually using the return string for anything. Commented Feb 2, 2016 at 16:49
  • yes it is a solution, but is it possible to return how i want ? Commented Feb 2, 2016 at 16:51
  • No, i can't return nil, because string can consist some values Commented Feb 2, 2016 at 16:52
  • 1
    @Arti Your code works fine for me, what's your environment ? Commented Feb 2, 2016 at 16:55
  • oh, yes, you are right, with any object it works, but: if isList { var results:[Kanna.XMLElement] = [] for node in doc.xpath(xpath) { results.append(node) } return results } Return expression of type '[XMLElement]' does not conform to 'AnyObject' Commented Feb 2, 2016 at 16:58

3 Answers 3

1

Your results variable needs to be of type AnyObject instead of [AnyObject]. Basically, you need to cast the array of AnyObjects to a single AnyObject

func someFunc(isList:Bool=false) -> AnyObject {
    if isList {
        var results: AnyObject = [11, "123", [], "22"]
        return results
    } else {
        var result = "123"
        return result
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

"AnyObject" is any object. [AnyObject] is an array, and arrays are values, not objects. And the other value you try to return is a string, which is also a value, not an object.

Your function should either return Any, or better yet an enum with two cases, one case [Any] and one case String.

Comments

0

Can you make it return Any?

func something(list: Bool = false) -> Any {
  if list {
    return [11, "123", [], "22"]
  } else {
    return "123"
  }
}

let result = something(true)
let result0 = something(false)

Any can represent an instance of any type at all, including function types.

The apple documentation suggests against using the Any protocol in this manner.

Note: Use Any and AnyObject only when you explicitly need the behavior and capabilities they provide. It is always better to be specific about the types you expect to work with in your code.

Apple Reference

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.