Mobile Development
Swift
Subjective
Oct 04, 2025
How do you implement custom operators in Swift?
Detailed Explanation
Swift allows defining custom operators with specific precedence and associativity.\n\n• **Operator Declaration:**\n\n// Declare operator\ninfix operator **: MultiplicationPrecedence\n\n// Implement operator\nfunc ** (base: Double, exponent: Double) -> Double {\n return pow(base, exponent)\n}\n\n// Usage\nlet result = 2.0 ** 3.0 // 8.0\n\n\n• **Precedence Groups:**\n\nprecedencegroup ExponentiationPrecedence {\n higherThan: MultiplicationPrecedence\n associativity: right\n}\n\ninfix operator **: ExponentiationPrecedence\n\n// Right associative: 2 ** 3 ** 2 = 2 ** (3 ** 2) = 512\n\n\n• **Operator Types:**\n\n// Prefix operator\nprefix operator √\nprefix func √(value: Double) -> Double {\n return sqrt(value)\n}\n\n// Postfix operator\npostfix operator !\npostfix func !(value: Int) -> Int {\n return (1...value).reduce(1, *)\n}\n\n// Usage\nlet root = √16.0 // 4.0\nlet factorial = 5! // 120\n\n\n• **Generic Operators:**\n\ninfix operator <>\n\nfunc <> (lhs: T?, rhs: T?) -> T? {\n return lhs ?? rhs\n}\n\nlet result = nil <> "default" <> "fallback" // "default"\n\n\n• **Best Practices:**\n• Use meaningful symbols\n• Follow existing conventions\n• Document behavior clearly\n• Consider readability impact
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts