Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AnyObject vs. Struct (Any)

I would like to create a method like this for my projects:

func print(obj: AnyObject) {
    if let rect = obj as? CGRect {
        println(NSStringFromCGRect(rect))
    }
    else if let size = obj as? CGSize {
        println(NSStringFromCGSize(size))
    }

    //...
}

But I can't because CGRect and CGSize are structs and do not conform to the AnyObject protocol. So, any ideas on how this could be done?

like image 512
Paulo Cesar Avatar asked Apr 01 '15 13:04

Paulo Cesar


2 Answers

Use Any instead of AnyObject.

Swift provides two special type aliases for working with non-specific types:

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

The Swift Programming Language

like image 58
Nikita Kukushkin Avatar answered Oct 15 '22 07:10

Nikita Kukushkin


@nkukushkin's answer is correct, however, if what you want is a function that behaves differently depending on whether it’s passed a CGRect or a CGStruct, you are better off with overloading:

func print(rect: CGRect) {
    println(NSStringFromCGRect(rect))
}

func print(size: CGSize) {
    println(NSStringFromCGSize(size))
}

In comparison, the Any will be both inefficient (converting your structs to Any and back, could have a big impact if you do this a lot in a tight loop), and non-typesafe (you can pass anything into that function, and it will only fail at runtime).

If your intention is to coerce both types into a common type and then do the same operation on it, you can create a 3rd overload that takes that type, and have the other two call it.

like image 37
Airspeed Velocity Avatar answered Oct 15 '22 07:10

Airspeed Velocity