Search This Blog

Saturday, October 14, 2017

iOS. Any vs AnyObject difference in Swift

Any and AnyObjects are not exactly data types. They are type alias.  Let's see Apple Documentation.

Swift provides two special types for working with nonspecific types:
  • Any can represent an instance of any type at all, including function types.
  • AnyObject can represent an instance of any class type.

Any Usage


Let's create array of Any and add items to that.
import UIKit

var items = [Any]()
items.append(1)
items.append("Special")
items.append(3.5)
items.append((55, 22))
items.append([1, 2, 3, 4])

func sum(_ a: Int, _ b: Int) -> Int {
    return (a + b)
}
let aSum = sum
items.append(aSum)

class Vehicle {
    var name: String
    init(_ name: String) {
        self.name = name
    }
}
items.append(Vehicle("MyCar"))

for item in items {
    print(item)
}

//1
//Special
//3.5
//(55, 22)
//[1, 2, 3, 4]
//(Function)
//__lldb_expr_102.Vehicle

It works fine because item of Any type can be added to array.

AnyObject Usage


Let's see how works AnyObject type. Here we create two classes and add their instances to array, works fine.
class Device {}
class Vehicle {}

var anyObjects: [AnyObject] = [Device(), Vehicle()]
// it works fine, because there only reference type instances - classes

But if we try to add non class types to AnyObject array we got error. Because Int and String are Structs in Swift, but Struct is value type.
var anyObjects: [AnyObject] = [1, "Test"]
// error: value of type 'Int' does not conform to expected element type 'AnyObject'

6 comments:

  1. There are many articles circulating on internet that exaggerate about Custom Website. But your article is an exception that made me understand it without any difficulty.

    ReplyDelete
  2. You've provided some really useful information; I've been looking for material like this, so please keep sharing it as much as you can. Best Custom Websites

    ReplyDelete
  3. Thank you for writing this quality informational content.Your writing technique is impressive and enjoyable to read. I'll come back for more fantastic material.
    Best wishes, and good luck.
    Custom Build Website

    ReplyDelete
  4. your article is unbelievable with accurate information. I see a lot of research after that and that is more than I expectedCustom Build Website

    ReplyDelete

  5. Great share!One of the best blogs I have Ever Seen. Keep going!
    Affordable SEO Packages New York

    ReplyDelete