Mobile Development
Swift
Subjective
Oct 04, 2025
What are generics in Swift and why are they useful?
Detailed Explanation
Generics enable writing flexible, reusable code that works with any type while maintaining type safety.\n\n• **Generic Functions:**\n\nfunc swapValues(_ a: inout T, _ b: inout T) {\n let temp = a\n a = b\n b = temp\n}\n\nvar x = 5, y = 10\nswapValues(&x, &y) // Works with Int\n\nvar str1 = "Hello", str2 = "World"\nswapValues(&str1, &str2) // Works with String\n\n\n• **Generic Types:**\n\nstruct Stack {\n var items: [Element] = []\n \n func push(_ item: Element) {\n items.append(item)\n }\n \n func pop() -> Element? {\n return items.popLast()\n }\n}\n\nvar intStack = Stack()\nvar stringStack = Stack()\n\n\n• **Type Constraints:**\n\nfunc findIndex(of valueToFind: T, in array: [T]) -> Int? {\n for (index, value) in array.enumerated() {\n if value == valueToFind {\n return index\n }\n }\n return nil\n}\n\n\n• **Benefits:**\n• Code reusability\n• Type safety\n• Performance optimization\n• Reduced code duplication
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts