Mobile Development
Swift
Subjective
Oct 04, 2025
What are the advanced features of Swift's pattern matching?
Detailed Explanation
Swift's pattern matching provides powerful and expressive ways to destructure and match data.\n\n• **Advanced Enum Matching:**\n\nenum Result {\n case success(Success)\n case failure(Failure)\n}\n\nenum NetworkError {\n case timeout\n case serverError(Int)\n case noConnection\n}\n\nlet result: Result = .failure(.serverError(500))\n\nswitch result {\ncase .success(let data) where data.count > 100:\n print("Large success: \(data)")\ncase .success(let data):\n print("Success: \(data)")\ncase .failure(.serverError(let code)) where code >= 500:\n print("Server error: \(code)")\ncase .failure(.serverError(let code)):\n print("Client error: \(code)")\ncase .failure(.timeout):\n print("Request timed out")\ncase .failure(.noConnection):\n print("No network connection")\n}\n\n\n• **Tuple and Value Binding:**\n\nlet coordinates = [(0, 0), (1, 0), (1, 1), (0, 1)]\n\nfor coordinate in coordinates {\n switch coordinate {\n case (0, 0):\n print("Origin")\n case (let x, 0):\n print("On x-axis at \(x)")\n case (0, let y):\n print("On y-axis at \(y)")\n case (let x, let y) where x == y:\n print("Diagonal at (\(x), \(y))")\n case (let x, let y):\n print("Point at (\(x), \(y))")\n }\n}\n\n\n• **Optional Pattern Matching:**\n\nlet optionals: [String?] = ["Hello", nil, "World", nil]\n\nfor case let .some(value) in optionals {\n print("Found: \(value)") // Only prints non-nil values\n}\n\n// Pattern matching in if-case\nlet someValue: Any = 42\nif let number as Int = someValue {\n print("Integer: \(number)")\n}\n\n\n• **Custom Pattern Matching:**\n\nstruct Range {
\n let lower: Int\n let upper: Int\n \n static func ~= (pattern: Range, value: Int) -> Bool {\n return pattern.lower <= value && value <= pattern.upper\n }\n}\n\nlet range = Range(lower: 10, upper: 20)\nlet value = 15\n\nswitch value {\ncase range:\n print("Value is in range")\ndefault:\n print("Value is out of range")\n}\n\n\n• **Expression Patterns:**\n\nlet numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\n// Filter using pattern matching\nlet evenNumbers = numbers.filter {\n if let x where x % 2 == 0 = $0 {\n return true\n }\n return false\n}\n\n// More concise\nlet evens = numbers.compactMap { $0 % 2 == 0 ? $0 : nil }\n
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts