0
0
Swiftprogramming~5 mins

Any and AnyObject types in Swift

Choose your learning style9 modes available
Introduction

Sometimes you want to store or work with values of any type without specifying exactly what type they are. Any and AnyObject help you do that in Swift.

When you want to hold different types of values in one place, like a list with numbers, strings, and objects.
When you need to work with objects from different classes without knowing their exact type.
When you want to write flexible functions that accept any kind of value or any class instance.
When you interact with APIs or libraries that return values of unknown types.
When you want to store references to class instances only, ignoring value types.
Syntax
Swift
var anyValue: Any
var anyObjectValue: AnyObject

Any can hold any kind of value: numbers, strings, structs, classes, functions, etc.

AnyObject can hold only class instances (objects).

Examples
You can assign any type of value to a variable of type Any.
Swift
var something: Any = 42
something = "Hello"
AnyObject holds a reference to a class instance.
Swift
class Dog {}
var pet: AnyObject = Dog()
An array of Any can hold mixed types.
Swift
var items: [Any] = [1, "two", 3.0]
AnyObject can be optional and hold class instances like NSString.
Swift
var object: AnyObject? = nil
object = NSString(string: "Hi")
Sample Program

This program shows how Any can hold different types in an array and how to check their types. It also shows AnyObject holding a class instance.

Swift
import Foundation

var mixedArray: [Any] = [10, "Swift", 3.14, true]

for item in mixedArray {
    switch item {
    case let number as Int:
        print("Integer: \(number)")
    case let text as String:
        print("String: \(text)")
    case let decimal as Double:
        print("Double: \(decimal)")
    case let flag as Bool:
        print("Boolean: \(flag)")
    default:
        print("Unknown type")
    }
}

class Cat {}

var pet: AnyObject = Cat()
print("Pet is a \(type(of: pet))")
OutputSuccess
Important Notes

Use Any when you want to store any kind of value, including value types and class instances.

Use AnyObject when you want to store only class instances (objects).

When using Any or AnyObject, you often need to check the actual type before using the value.

Summary

Any can hold any type of value.

AnyObject can hold only class instances.

They help write flexible code that works with unknown or mixed types.