ios - AnyObject vs. Struct (Any) -
i create method 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 can't because cgrect , cgsize structs , not conform anyobject protocol. so, ideas on how done?
@nkukushkin's answer correct, however, if want function behaves differently depending on whether it’s passed cgrect or cgstruct, better off overloading:
func print(rect: cgrect) {     println(nsstringfromcgrect(rect)) }  func print(size: cgsize) {     println(nsstringfromcgsize(size)) }   in comparison, any both inefficient (converting structs any , back, have big impact if lot in tight loop), , non-typesafe (you can pass function, , fail @ runtime).
if intention coerce both types common type , same operation on it, can create 3rd overload takes type, , have other 2 call it.
Comments
Post a Comment