Swift Built-in Functions
Essential functions provided by Swift standard library
⚡ What are Built-in Functions?
Swift built-in functions are pre-defined functions available globally without importing libraries. They handle common tasks like printing, type conversion, mathematical operations, and collection manipulation efficiently.
// Common built-in functions
print("Hello, World!") // Output text
let length = "Swift".count // String length
let maximum = max(10, 20) // Find maximum
let minimum = min(5, 15) // Find minimum
Function Categories
Output Functions
Display and debug information
Math Functions
Mathematical operations
Type Functions
Type checking and conversion
Collection Functions
Work with arrays and sequences
🔹 Output and Debug Functions
Functions for displaying information and debugging:
// Basic printing
print("Hello, Swift!")
print("Value:", 42)
print("Multiple", "values", "here")
// Print with separator and terminator
print("A", "B", "C", separator: "-", terminator: "!\n")
// Output: A-B-C!
// Debug printing (shows more detail)
let array = [1, 2, 3]
debugPrint(array) // Shows type information
// Dump - detailed object description
dump(array)
// Shows complete structure
// String interpolation in print
let name = "Swift"
let version = 5.9
print("Welcome to \(name) \(version)!")
🔹 Mathematical Functions
Built-in functions for mathematical operations:
// Basic math functions
let numbers = [-5, 10, 3, -2, 8]
print(abs(-5)) // 5 (absolute value)
print(max(10, 20)) // 20 (maximum)
print(min(10, 20)) // 10 (minimum)
print(max(numbers)) // 10 (maximum in array)
// Advanced math (import Foundation for more)
import Foundation
print(sqrt(16)) // 4.0 (square root)
print(pow(2, 3)) // 8.0 (power)
print(ceil(4.3)) // 5.0 (ceiling)
print(floor(4.7)) // 4.0 (floor)
print(round(4.6)) // 5.0 (round)
// Random numbers
print(Int.random(in: 1...10)) // Random integer 1-10
print(Double.random(in: 0.0...1.0)) // Random double 0-1
🔹 Type Conversion Functions
Convert between different data types:
// String conversions
let number = 42
let text = String(number) // "42"
let decimal = String(3.14159) // "3.14159"
// Number conversions
let stringNumber = "123"
let integer = Int(stringNumber) // Optional(123)
let double = Double("3.14") // Optional(3.14)
// Safe conversion with nil-coalescing
let safeInt = Int("abc") ?? 0 // 0 (default value)
// Type checking
let value: Any = "Hello"
print(type(of: value)) // String
// Character and ASCII
let char: Character = "A"
let ascii = char.asciiValue // Optional(65)
// Boolean conversion
let boolFromInt = Bool(truncating: 1) // true
let boolFromString = Bool("true") // nil (no direct conversion)
🔹 Collection Functions
Functions for working with arrays and sequences:
// Zip - combine two sequences
let names = ["Alice", "Bob", "Charlie"]
let ages = [25, 30, 35]
let combined = zip(names, ages)
for (name, age) in combined {
print("\(name) is \(age) years old")
}
// Stride - create number sequences
for i in stride(from: 0, to: 10, by: 2) {
print(i) // 0, 2, 4, 6, 8
}
for i in stride(from: 10, through: 0, by: -2) {
print(i) // 10, 8, 6, 4, 2, 0
}
// Repeat element
let repeated = repeatElement("Swift", count: 3)
let array = Array(repeated) // ["Swift", "Swift", "Swift"]
// Sequence functions
let numbers = [1, 2, 3, 4, 5]
print(numbers.count) // 5
print(numbers.isEmpty) // false
print(numbers.first) // Optional(1)
print(numbers.last) // Optional(5)
🔹 String Functions
Built-in functions for string manipulation:
let text = "Hello, Swift!"
// String properties and methods
print(text.count) // 13 (character count)
print(text.isEmpty) // false
print(text.uppercased()) // "HELLO, SWIFT!"
print(text.lowercased()) // "hello, swift!"
// String checking
print(text.hasPrefix("Hello")) // true
print(text.hasSuffix("Swift!")) // true
print(text.contains("Swift")) // true
// String manipulation
let trimmed = " spaces ".trimmingCharacters(in: .whitespaces)
print(trimmed) // "spaces"
// String components
let words = text.components(separatedBy: " ")
print(words) // ["Hello,", "Swift!"]
// Character operations
for char in text {
if char.isLetter {
print(char, terminator: "") // HelloSwift
}
}
🔹 Memory and Performance Functions
Functions for memory management and performance:
// Memory size functions
print(MemoryLayout.size) // 8 (bytes)
print(MemoryLayout.stride) // Memory stride
// Swap function
var a = 10
var b = 20
swap(&a, &b)
print(a, b) // 20, 10
// Assert functions (debug builds only)
let age = 25
assert(age >= 0, "Age cannot be negative")
// Precondition (always checked)
precondition(age >= 0, "Age must be positive")
// Fatal error (terminates program)
// fatalError("Something went wrong")
// Measure execution time
import Foundation
let startTime = CFAbsoluteTimeGetCurrent()
// ... some code ...
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed: \(timeElapsed) seconds")