← Back to archive

Development · Swift

Any, AnyObject, and function types in Swift

Understand broad value types, argument labels, and functions as first-class values.

Read the Korean original on Velog ↗English translation

Development archive cover

Swift is statically typed, but Any and AnyObject can represent values whose concrete types vary. Functions also have types and can be stored, passed, and returned.

Any and AnyObject

Any can represent a value of any type, including value and reference types. AnyObject represents class instances.

var value: Any = 100
value = "Swift"

final class Profile {}
var object: AnyObject = Profile()

var optionalValue: Any? = nil

Using a broad type hides concrete type information and often requires a cast later. Keep its scope narrow. Use an optional when absence needs to be represented directly.

Parameters and function types

func greet(_ name: String, job: String = "designer") {
    print("Hi, I'm \(name), \(job).")
}

let action: (String, String) -> Void = greet
action("snack", "developer")

func run(_ action: (String, String) -> Void) {
    action("snack", "designer")
}

Default arguments reduce repetition, while argument labels explain the role of each value. Functions are first-class values: they can be assigned to variables, passed as arguments, and returned from other functions.

← Back to archive