Swift Attributes

Metadata and annotations for Swift declarations

🏷️ What are Swift Attributes?

Swift attributes provide metadata about declarations and types. They give additional information to the compiler about how to process your code and can modify behavior or provide warnings.


// Attribute examples
@available(iOS 13.0, *)
@objc
class NetworkManager {
    @discardableResult
    func fetchData() -> Bool {
        return true
    }
}
                                    

Output:

NetworkManager with availability and Objective-C compatibility attributes

Common Swift Attributes

📱

@available

Platform and version availability

@available(iOS 14.0, *)
🔄

@objc

Objective-C compatibility

@objc func handleTap()
🗑️

@discardableResult

Allow ignoring return values

@discardableResult
⚠️

@deprecated

Mark as deprecated

@deprecated("Use newMethod")

🔹 Availability Attributes

Control when your code can be used on different platforms:

// Available on iOS 13.0 and later
@available(iOS 13.0, *)
func useSwiftUI() {
    print("Using SwiftUI features")
}

// Available on multiple platforms
@available(iOS 13.0, macOS 10.15, watchOS 6.0, *)
func crossPlatformFeature() {
    print("Works on iOS, macOS, and watchOS")
}

// Deprecated with message
@available(*, deprecated, message: "Use newAPIMethod instead")
func oldAPIMethod() {
    print("This method is deprecated")
}

// Unavailable
@available(*, unavailable, message: "This feature is not supported")
func unsupportedFeature() {
    // This will cause a compile error if used
}

Output:

Using SwiftUI features
Works on iOS, macOS, and watchOS

🔹 Function Attributes

Attributes that modify function behavior:

class DataProcessor {
    // Allow ignoring return value
    @discardableResult
    func processData(_ data: String) -> Bool {
        print("Processing: \(data)")
        return true
    }
    
    // Objective-C compatible
    @objc func handleNotification() {
        print("Notification received")
    }
    
    // Inline function
    @inline(__always)
    func fastCalculation() -> Int {
        return 42
    }
    
    // No return attribute
    @noreturn
    func fatalError() -> Never {
        Swift.fatalError("Critical error occurred")
    }
}

let processor = DataProcessor()
processor.processData("user input") // Return value can be ignored

Output:

Processing: user input

🔹 Property Wrapper Attributes

Custom attributes for property behavior:

// Property wrapper definition
@propertyWrapper
struct Capitalized {
    private var value: String = ""
    
    var wrappedValue: String {
        get { value }
        set { value = newValue.capitalized }
    }
}

// Using property wrapper
struct Person {
    @Capitalized var firstName: String
    @Capitalized var lastName: String
    
    var fullName: String {
        return "\(firstName) \(lastName)"
    }
}

var person = Person()
person.firstName = "john"
person.lastName = "doe"
print(person.fullName) // "John Doe"

Output:

John Doe

🔹 Testing Attributes

Attributes commonly used in testing:

import XCTest

class MyTests: XCTestCase {
    
    // Test method
    func testExample() {
        XCTAssertTrue(true)
    }
    
    // Test with expected failure
    @available(*, deprecated)
    func testDeprecatedFeature() {
        // Test deprecated functionality
    }
    
    // Performance test
    func testPerformance() {
        measure {
            // Performance testing code
            for _ in 0..<1000 {
                _ = String(describing: Date())
            }
        }
    }
}

Output:

Test methods with various attributes for different testing scenarios

🧠 Test Your Knowledge

Which attribute allows you to ignore a function's return value?