Type Aliases

typealias AnyClass

The protocol to which all class types implicitly conform.

You can use the AnyClass protocol as the concrete type for an instance of any class. When you do, all known @objc class methods and properties are available as implicitly unwrapped optional methods and properties, respectively. For example:

class IntegerRef {
    @objc class func getDefaultValue() -> Int {
        return 42
    }
}

func getDefaultValue(_ c: AnyClass) -> Int? {
    return c.getDefaultValue?()
}

The getDefaultValue(_:) function uses optional chaining to safely call the implicitly unwrapped class method on c. Calling the function with different class types shows how the getDefaultValue() class method is only conditionally available.

print(getDefaultValue(IntegerRef.self))
// Prints "Optional(42)"

print(getDefaultValue(NSString.self))
// Prints "nil"

Declaration

public typealias AnyClass = AnyObject.Type
typealias AnyObject

The protocol to which all classes implicitly conform.

You use AnyObject when you need the flexibility of an untyped object or when you use bridged Objective-C methods and properties that return an untyped result. AnyObject can be used as the concrete type for an instance of any class, class type, or class-only protocol. For example:

class FloatRef {
    let value: Float
    init(_ value: Float) {
        self.value = value
    }
}

let x = FloatRef(2.3)
let y: AnyObject = x
let z: AnyObject = FloatRef.self

AnyObject can also be used as the concrete type for an instance of a type that bridges to an Objective-C class. Many value types in Swift bridge to Objective-C counterparts, like String and Int.

let s: AnyObject = "This is a bridged string." as NSString
print(s is NSString)
// Prints "true"

let v: AnyObject = 100 as NSNumber
print(type(of: v))
// Prints "__NSCFNumber"

The flexible behavior of the AnyObject protocol is similar to Objective-C's id type. For this reason, imported Objective-C types frequently use AnyObject as the type for properties, method parameters, and return values.

Casting AnyObject Instances to a Known Type

Objects with a concrete type of AnyObject maintain a specific dynamic type and can be cast to that type using one of the type-cast operators (as, as?, or as!).

This example uses the conditional downcast operator (as?) to conditionally cast the s constant declared above to an instance of Swift's String type.

if let message = s as? String {
    print("Successful cast to String: \(message)")
}
// Prints "Successful cast to String: This is a bridged string."

If you have prior knowledge that an AnyObject instance has a particular type, you can use the unconditional downcast operator (as!). Performing an invalid cast triggers a runtime error.

let message = s as! String
print("Successful cast to String: \(message)")
// Prints "Successful cast to String: This is a bridged string."

let badCase = v as! String
// Runtime error

Casting is always safe in the context of a switch statement.

let mixedArray: [AnyObject] = [s, v]
for object in mixedArray {
    switch object {
    case let x as String:
        print("'\(x)' is a String")
    default:
        print("'\(object)' is not a String")
    }
}
// Prints "'This is a bridged string.' is a String"
// Prints "'100' is not a String"

Accessing Objective-C Methods and Properties

When you use AnyObject as a concrete type, you have at your disposal every @objc method and property---that is, methods and properties imported from Objective-C or marked with the @objc attribute. Because Swift can't guarantee at compile time that these methods and properties are actually available on an AnyObject instance's underlying type, these @objc symbols are available as implicitly unwrapped optional methods and properties, respectively.

This example defines an IntegerRef type with an @objc method named getIntegerValue().

class IntegerRef {
    let value: Int
    init(_ value: Int) {
        self.value = value
    }

    @objc func getIntegerValue() -> Int {
        return value
    }
}

func getObject() -> AnyObject {
    return IntegerRef(100)
}

let obj: AnyObject = getObject()

In the example, obj has a static type of AnyObject and a dynamic type of IntegerRef. You can use optional chaining to call the @objc method getIntegerValue() on obj safely. If you're sure of the dynamic type of obj, you can call getIntegerValue() directly.

let possibleValue = obj.getIntegerValue?()
print(possibleValue)
// Prints "Optional(100)"

let certainValue = obj.getIntegerValue()
print(certainValue)
// Prints "100"

If the dynamic type of obj doesn't implement a getIntegerValue() method, the system returns a runtime error when you initialize certainValue.

Alternatively, if you need to test whether obj.getIntegerValue() exists, use optional binding before calling the method.

if let f = obj.getIntegerValue {
    print("The value of 'obj' is \(f())")
} else {
    print("'obj' does not have a 'getIntegerValue()' method")
}
// Prints "The value of 'obj' is 100"

Declaration

public typealias AnyObject
typealias BooleanLiteralType

The default type for an otherwise-unconstrained Boolean literal.

When you create a constant or variable using one of the Boolean literals true or false, the resulting type is determined by the BooleanLiteralType alias. For example:

let isBool = true
print("isBool is a '\(type(of: isBool))'")
// Prints "isBool is a 'Bool'"

The type aliased by BooleanLiteralType must conform to the ExpressibleByBooleanLiteral protocol.

Declaration

public typealias BooleanLiteralType = Bool
typealias CBool

The C '_Bool' and C++ 'bool' type.

Declaration

public typealias CBool = Bool
typealias CChar

The C 'char' type.

This will be the same as either CSignedChar (in the common case) or CUnsignedChar, depending on the platform.

Declaration

public typealias CChar = Int8
typealias CChar16

The C++11 'char16_t' type, which has UTF-16 encoding.

Declaration

public typealias CChar16 = UInt16
typealias CChar32

The C++11 'char32_t' type, which has UTF-32 encoding.

Declaration

public typealias CChar32 = Unicode.Scalar
typealias CDouble

The C 'double' type.

Declaration

public typealias CDouble = Double
typealias CFloat

The C 'float' type.

Declaration

public typealias CFloat = Float
typealias CInt

The C 'int' type.

Declaration

public typealias CInt = Int32
typealias CLong

Declaration

public typealias CLong = Int
typealias CLongDouble

Declaration

public typealias CLongDouble = Float80
typealias CLongLong

The C 'long long' type.

Declaration

public typealias CLongLong = Int64
typealias CShort

The C 'short' type.

Declaration

public typealias CShort = Int16
typealias CSignedChar

The C 'signed char' type.

Declaration

public typealias CSignedChar = Int8
typealias CUnsignedChar

The C 'unsigned char' type.

Declaration

public typealias CUnsignedChar = UInt8
typealias CUnsignedInt

The C 'unsigned int' type.

Declaration

public typealias CUnsignedInt = UInt32
typealias CUnsignedLong

Declaration

public typealias CUnsignedLong = UInt
typealias CUnsignedLongLong

The C 'unsigned long long' type.

Declaration

public typealias CUnsignedLongLong = UInt64
typealias CUnsignedShort

The C 'unsigned short' type.

Declaration

public typealias CUnsignedShort = UInt16
typealias CWideChar

The C++ 'wchar_t' type.

Declaration

public typealias CWideChar = Unicode.Scalar
typealias Codable

A type that can convert itself into and out of an external representation.

Codable is a type alias for the Encodable and Decodable protocols. When you use Codable as a type or a generic constraint, it matches any type that conforms to both protocols.

Declaration

public typealias Codable = Decodable & Encodable
typealias CountableClosedRange

Declaration

public typealias CountableClosedRange<Bound> = ClosedRange<Bound> where Bound: Strideable, Bound.Stride: SignedInteger
typealias CountablePartialRangeFrom

Declaration

public typealias CountablePartialRangeFrom<Bound> = PartialRangeFrom<Bound> where Bound: Strideable, Bound.Stride: SignedInteger
typealias CountableRange

Declaration

public typealias CountableRange<Bound> = Range<Bound> where Bound: Strideable, Bound.Stride: SignedInteger
typealias DictionaryIndex

Declaration

public typealias DictionaryIndex<Key, Value> = Dictionary<Key, Value>.Index where Key: Hashable
typealias DictionaryIterator

Declaration

public typealias DictionaryIterator<Key, Value> = Dictionary<Key, Value>.Iterator where Key: Hashable
typealias DictionaryLiteral

Declaration

@available(swift, deprecated: 5.0, renamed: "KeyValuePairs") public typealias DictionaryLiteral<Key, Value> = KeyValuePairs<Key, Value>
typealias EnumeratedIterator

Declaration

@available(swift, deprecated: 4.2, renamed: "EnumeratedSequence.Iterator") public typealias EnumeratedIterator<T> = EnumeratedSequence<T>.Iterator where T: Sequence
typealias ExtendedGraphemeClusterType

The default type for an otherwise-unconstrained Unicode extended grapheme cluster literal.

Declaration

public typealias ExtendedGraphemeClusterType = String
typealias FlattenCollection

Declaration

public typealias FlattenCollection<T> = FlattenSequence<T> where T: Collection, T.Element: Collection
typealias Float32

A 32-bit floating point type.

Declaration

public typealias Float32 = Float
typealias Float64

A 64-bit floating point type.

Declaration

public typealias Float64 = Double
typealias FloatLiteralType

The default type for an otherwise-unconstrained floating point literal.

Declaration

public typealias FloatLiteralType = Double
typealias IntegerLiteralType

The default type for an otherwise-unconstrained integer literal.

Declaration

public typealias IntegerLiteralType = Int
typealias LazyCollection

A collection containing the same elements as a Base collection, but on which some operations such as map and filter are implemented lazily.

  • See also: LazySequenceProtocol, LazyCollection

Declaration

public typealias LazyCollection<T> = LazySequence<T> where T: Collection
typealias LazyDropWhileCollection

A lazy wrapper that includes the elements of an underlying collection after any initial consecutive elements that satisfy a predicate.

Note: The performance of accessing startIndex, first, or any methods that depend on startIndex depends on how many elements satisfy the predicate at the start of the collection, and may not offer the usual performance given by the Collection protocol. Be aware, therefore, that general operations on lazy collections may not have the documented complexity.

Declaration

public typealias LazyDropWhileCollection<T> = LazyDropWhileSequence<T> where T: Collection
typealias LazyFilterCollection

A lazy Collection wrapper that includes the elements of an underlying collection that satisfy a predicate.

Note: The performance of accessing startIndex, first, any methods that depend on startIndex, or of advancing an index depends on how sparsely the filtering predicate is satisfied, and may not offer the usual performance given by Collection. Be aware, therefore, that general operations on LazyFilterCollection instances may not have the documented complexity.

Declaration

public typealias LazyFilterCollection<T> = LazyFilterSequence<T> where T: Collection
typealias LazyMapCollection

A Collection whose elements consist of those in a Base Collection passed through a transform function returning Element. These elements are computed lazily, each time they're read, by calling the transform function on a base element.

Declaration

public typealias LazyMapCollection<T, U> = LazyMapSequence<T, U> where T: Collection
typealias LazyPrefixWhileCollection

A lazy collection wrapper that includes the initial consecutive elements of an underlying collection that satisfy a predicate.

Note: The performance of accessing endIndex depends on how many elements satisfy the predicate at the start of the collection, and might not offer the usual performance given by the Collection protocol. Accessing endIndex, the last property, or calling methods that depend on moving indices might not have the documented complexity.

Declaration

public typealias LazyPrefixWhileCollection<T> = LazyPrefixWhileSequence<T> where T: Collection
typealias PlaygroundQuickLook

The sum of types that can be used as a Quick Look representation.

The PlaygroundQuickLook protocol is deprecated, and will be removed from the standard library in a future Swift release. To customize the logging of your type in a playground, conform to the CustomPlaygroundDisplayConvertible protocol, which does not use the PlaygroundQuickLook enum.

If you need to provide a customized playground representation in Swift 4.0 or Swift 3.2 or earlier, use a conditional compilation block:

#if swift(>=4.1) || (swift(>=3.3) && !swift(>=4.0))
    // With Swift 4.1 and later (including Swift 3.3 and later), use
    // the CustomPlaygroundDisplayConvertible protocol.
#else
    // With Swift 4.0 and Swift 3.2 and earlier, use PlaygroundQuickLook
    // and the CustomPlaygroundQuickLookable protocol.
#endif

Declaration

@available(swift, deprecated: 4.2, message: "PlaygroundQuickLook will be removed in a future Swift version. For customizing how types are presented in playgrounds, use CustomPlaygroundDisplayConvertible instead.") public typealias PlaygroundQuickLook
typealias SetIndex

Declaration

public typealias SetIndex<Element> = Set<Element>.Index where Element: Hashable
typealias SetIterator

Declaration

public typealias SetIterator<Element> = Set<Element>.Iterator where Element: Hashable
typealias StringLiteralType

The default type for an otherwise-unconstrained string literal.

Declaration

public typealias StringLiteralType = String
typealias UTF16

Declaration

public typealias UTF16 = Unicode.UTF16
typealias UTF32

Declaration

public typealias UTF32 = Unicode.UTF32
typealias UTF8

Declaration

public typealias UTF8 = Unicode.UTF8
typealias UnboundedRange

The type of an unbounded range operator.

Declaration

public typealias UnboundedRange = (UnboundedRange_) -> ()
typealias UnfoldFirstSequence

The return type of sequence(first:next:).

Declaration

public typealias UnfoldFirstSequence<T> = UnfoldSequence<T, (T?, Bool)>
typealias UnicodeScalar

Declaration

public typealias UnicodeScalar = Unicode.Scalar
typealias UnicodeScalarType

The default type for an otherwise-unconstrained unicode scalar literal.

Declaration

public typealias UnicodeScalarType = String
typealias Void

The return type of functions that don't explicitly specify a return type, that is, an empty tuple ().

When declaring a function or method, you don't need to specify a return type if no value will be returned. However, the type of a function, method, or closure always includes a return type, which is Void if otherwise unspecified.

Use Void or an empty tuple as the return type when declaring a closure, function, or method that doesn't return a value.

// No return type declared:
func logMessage(_ s: String) {
    print("Message: \(s)")
}

let logger: (String) -> Void = logMessage
logger("This is a void function")
// Prints "Message: This is a void function"

Declaration

public typealias Void = ()