Swift: Any/ AnyObject/ AnyHashable Differences
5 (1)

Although in normal cases, you should be specific in defining data types, swift offers Any, AnyObject, and AnyHashable.

Any can represent an instance of any type, including functions, instance of a class, struct, or enum, it’s more general than AnyObject, where AnyObject is a protocol all classes indirectly conform to.

AnyObject is useful when using Objetive-C / Swift, some parts of Objective-C use this protocol to enhance compatibility with Swift, it’s equivelant to ‘id’ in Objective-C.

so, when to use Any / AnyObject ?
say you have a dictionary..

let anyStuff: [Any] = [1,”z”,3,[]]

If your data will be used only in Swift code, then you should use Any because your types (Int, Double, Float, String, Array, and Dictionary) are not objects.

If it will be passed to Objective-C code that expect an NSDictionary, then go with AnyObject.

AnyHashable is a super-type that is defined as a struct, it was introduced in Swift 3 standard library, it’s used to bring untyped sets and dictionaries from Objective-C to Swift.

public struct Notification : ReferenceConvertible, Equatable, Hashable {
    /// Storage for values or objects related to this notification.
    public var userInfo: [AnyHashable : Any]?
}
Click to rate this post!
[Total: 1 Average: 5]

Swift Basic Data Types & Type Inference
5 (1)

Swift is strongly typed, data should either be explicitly assigned or inferred, the main basic data types that come with swift are

TypeDescription
Charactera 16-bit Unicode character like “a” or “/”
Stringrepresents textual data like “Hello”
Floatrepresents 32-bit floating-point number
Doublerepresents 64-bit floating-point number
Boollogical value: true or false
Tuplesgroups multiple values in single value
Intinteger, a whole number
UIntunsigned integer, a whole number
Int81 byte integer
Int324 bytes integer
Int648 bytes integer
UInt81 byte unsigned integer
UInt324 bytes unsigned integer
UInt648 bytes unsigned integer


On a 32-bit device, Int has the size of Int32, on 64-bit devices, Int has the size of Int64, same goes for UInt.

Swift has a feature where it can infer the type of the data directly, for example the variable level here is infered to be an Int

var level = 12

you can explicitly determine the type directly

var level: Int = 17
Click to rate this post!
[Total: 1 Average: 5]