11

I have,

struct S {}

Along with,

func y (x: S) -> AnyObject {}

In Swift 2, is it possible to, within y(),

return x

My current code:

struct S {let value: Int = 0}
let x = S()
func y(x: S) -> AnyObject {return x}

Yields the following error:

return expression of type 'S' does not conform to type 'AnyObject'

Is there a way to mitigate this?

4
  • 1
    Is there any reason why your struct can't be a class that conforms to AnyObject? Commented Nov 25, 2015 at 16:50
  • I use a struct here because I create several hundreds of them, and as such, making the struct a class would not only slow down my application, but also make it less efficient and more error prone. See: stackoverflow.com/questions/24232799/… Commented Nov 25, 2015 at 16:56
  • 2
    I think you are reading too much into that discussion. Structs are value objects, which lets the compiler make some simplifying assumptions, but in the real world it's likely that you won't be able to detect the difference in performance. If you need a class object, (inheritance, need to pass by reference, etc.) then use one. Commented Nov 25, 2015 at 17:41
  • Alright, I changed it to a class and it works. Thanks for the help. Commented Nov 25, 2015 at 17:45

1 Answer 1

28

A Struct cannot conform to AnyObject. It can only conform to Any

Sign up to request clarification or add additional context in comments.

1 Comment

Could I create a controller class that takes the struct that operates on the struct?

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.