print() (Built-in)

Dart's standard output function. Suitable for rapid log output in learning stages and simple scripts as simplest debugging means. Immediately available without configuration, but has feature limitations in full-scale application development.

loggingSwiftdebuggingconsole outputlearningbuilt-in

Library

print() (Built-in)

Overview

Swift's standard output function serves as the most simple and accessible debugging tool available to developers. Immediately available without any configuration, it's perfectly suited for rapid log output during Swift learning stages and quick debugging sessions. However, for serious application development, it has functional limitations and poses performance and security challenges since it's not automatically disabled in production builds.

Details

The print() function is a fundamental output capability included in Swift's standard library, representing one of the first logging methods developers encounter when learning Swift. Primarily designed for output to the Xcode debug console, it can easily display various data types including strings, numbers, and objects. It supports variadic arguments and allows output customization through separator and terminator parameters, providing flexibility in how information is presented.

Key Features

  • No Configuration Required: Immediately available in any Swift project
  • Variadic Arguments Support: Output multiple values in a single call
  • Customizable: Control output format with separator and terminator parameters
  • Type Safe: Fully integrated with Swift's type system
  • Debug Only: Outputs exclusively to Xcode console
  • Simple API: Minimal learning curve required

Pros and Cons

Pros

  • Available immediately in Swift projects without additional setup
  • Minimal learning curve, making it beginner-friendly
  • Flexible output through variadic arguments and customization parameters
  • Direct verification in Xcode debug environment enhances development efficiency
  • Fully integrated with Swift type system ensuring type safety
  • Optimal for quick debugging with simple API

Cons

  • Not automatically disabled in production builds, affecting performance
  • Output limited to Xcode console with no log persistence
  • Lacks log levels and filtering capabilities
  • Cannot integrate with network logs or system logs
  • Unsuitable for structured log management in large-scale applications
  • Requires manual removal before App Store submission

Reference Pages

Code Examples

Basic Output

// Basic string output
print("Hello, Swift!")
// Output: Hello, Swift!

// Variable output
let name = "John Doe"
let age = 30
print("Name: \(name), Age: \(age)")
// Output: Name: John Doe, Age: 30

// Multiple values in single call
print("Name:", name, "Age:", age)
// Output: Name: John Doe Age: 30

Customization Parameters

// separator parameter (custom delimiter)
print("Apple", "Banana", "Cherry", separator: " | ")
// Output: Apple | Banana | Cherry

print("Value1", "Value2", "Value3", separator: ", ")
// Output: Value1, Value2, Value3

// terminator parameter (custom ending)
print("Line 1", terminator: " ")
print("continued")
// Output: Line 1 continued

print("No newline", terminator: "")
print("immediately after")
// Output: No newlineimmediately after

Debugging Applications

// Function execution tracking
func calculateSum(_ a: Int, _ b: Int) -> Int {
    print("calculateSum called: a=\(a), b=\(b)")
    let result = a + b
    print("Calculation result: \(result)")
    return result
}

let sum = calculateSum(5, 3)
// Output: calculateSum called: a=5, b=3
// Output: Calculation result: 8

// Conditional flow debugging
let score = 85
if score >= 90 {
    print("Excellent: \(score) points")
} else if score >= 70 {
    print("Good: \(score) points")  // This line executes
} else {
    print("Needs improvement: \(score) points")
}
// Output: Good: 85 points

Objects and Collections Output

// Array output
let fruits = ["apple", "banana", "orange"]
print("Fruit list:", fruits)
// Output: Fruit list: ["apple", "banana", "orange"]

// Dictionary output
let person = ["name": "Jane Smith", "age": "25", "city": "New York"]
print("Person info:", person)
// Output: Person info: ["name": "Jane Smith", "age": "25", "city": "New York"]

// Custom object output
struct User {
    let id: Int
    let name: String
}

let user = User(id: 1, name: "Bob Johnson")
print("User:", user)
// Output: User: User(id: 1, name: "Bob Johnson")

Advanced Format Output

// String interpolation for detailed output
let temperature = 23.5
let humidity = 65.2
print("Weather info - Temperature: \(String(format: "%.1f", temperature))°C, Humidity: \(String(format: "%.1f", humidity))%")
// Output: Weather info - Temperature: 23.5°C, Humidity: 65.2%

// Individual array element output
let numbers = [1, 2, 3, 4, 5]
print("Number list:", numbers.map { "[\($0)]" }.joined(separator: " "))
// Output: Number list: [1] [2] [3] [4] [5]

// Error handling usage
enum NetworkError: Error {
    case noConnection
    case timeout
}

func simulateNetworkCall() throws {
    print("Network call started")
    // Simulation
    throw NetworkError.timeout
}

do {
    try simulateNetworkCall()
    print("Network call successful")
} catch {
    print("Error occurred: \(error)")
}
// Output: Network call started
// Output: Error occurred: timeout

Practical Debugging Patterns

// Function input parameter verification
func processData(_ data: [String]) {
    print("🔍 processData called with \(data.count) items")
    print("📊 Data: \(data)")
    
    for (index, item) in data.enumerated() {
        print("  [\(index)]: \(item)")
    }
}

processData(["ItemA", "ItemB", "ItemC"])
// Output: 🔍 processData called with 3 items
// Output: 📊 Data: ["ItemA", "ItemB", "ItemC"]
// Output:   [0]: ItemA
// Output:   [1]: ItemB
// Output:   [2]: ItemC

// Process flow tracking
print("=== Application Start ===")
print("⚙️  Loading configuration...")
print("✅ Configuration loaded")
print("🌐 Checking network connection...")
print("✅ Network connection verified")
print("=== Initialization Complete ===")