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?

Brandon Bradley
  • 3,160
  • 4
  • 22
  • 39
  • 1
    Is there any reason why your struct can't be a class that conforms to `AnyObject`? – JAL Nov 25 '15 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: http://stackoverflow.com/questions/24232799/why-choose-struct-over-class – Brandon Bradley Nov 25 '15 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. – Duncan C Nov 25 '15 at 17:41
  • Alright, I changed it to a class and it works. Thanks for the help. – Brandon Bradley Nov 25 '15 at 17:45

1 Answers1

28

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

Duncan C
  • 128,072
  • 22
  • 173
  • 272