YouTip LogoYouTip

Swift Extensions

Extensions add new functionality to an existing class, structure, or enumeration type.\\n\\nExtensions can add new functionality to a type, but they cannot override existing functionality.\\n\\nExtensions in Swift can:\\n\\n* Add computed instance properties and computed type properties\\n* Define instance methods and type methods\\n* Provide new initializers\\n* Define subscripts\\n* Define and use new nested types\\n* Make an existing type conform to a protocol\\n\\n### Syntax\\n\\nExtensions are declared using the **extension** keyword:\\n\\nextension SomeType { // Add new functionality to SomeType here}\\nAn extension can extend an existing type to adapt it to one or more protocols. The syntax format is as follows:\\n\\nextension SomeType: SomeProtocol, AnotherProctocol { // Protocol implementation goes here}\\n\\n* * *\\n\\n## Computed Properties\\n\\nExtensions can add computed instance properties and computed type properties to existing types.\\n\\n### Instance\\n\\nThe following example adds 5 computed instance properties to the Int type and extends its functionality:\\n\\nextension Int { var add: Int {return self + 100 } var sub: Int { return self - 10 } var mul: Int { return self * 10 } var div: Int { return self / 5 }} let addition = 3. Value after addition:addprint("Value after addition:\\\\(addition)") let subtraction = 120. Output: 6printsubprint("Value after subtraction:\\\\(subtraction)") let multiplication = 39. Mixed operation result: 154mulprint("Value after multiplication:\\\\(multiplication)") let division = 55. Value after multiplication:divprint("Value after division: \\\\(division)")let mix = 30.add + 34. Value after subtraction:subprint("Mixed operation result:\\\\(mix)")\\nThe output of the above program execution is:\\n\\nValue after addition:103Value after subtraction:110Value after multiplication:390Value after division: 11Mixed operation result: 154\\n\\n* * *\\n\\n## Initializers\\n\\nExtensions can add new initializers to existing types.\\n\\nThis allows you to extend other types to take your own custom types as initializer parameters, or to provide additional initialization options that are not included in the original implementation of the type.\\n\\nExtensions can add new convenience initializers init() to classes, but they cannot add new designated initializers or deinitializers deinit() to classes.\\n\\nstruct sum { var num1 = 100, num2 = 200}struct diff { var no1 = 200, no2 = 100}struct mult { var a = sum() var b = diff()} extension mult { init(x: sum, y: diff) { _ = x.num1 + x.num2 _ = y.no1 + y.no2 }}let a = sum(num1: 100, num2: 200)let b = diff(no1: 200, no2: 100)let getMult = mult(x: a, y: b)print("getMult sum\\\\(getMult.a.num1, getMult.a.num2)")print("getMult diff\\\\(getMult.b.no1, getMult.b.no2)")\\nThe output of the above program execution is:\\n\\ngetMult sum(100, 200) getMult diff(200, 100)\\n\\n* * *\\n\\n## Methods\\n\\nExtensions can add new instance methods and type methods to existing types.\\n\\nThe following example adds a new instance method named topics to the Int type:\\n\\nextension Int { func topics(summation: () -> ()) { for _ in 0.. ()`, indicating that the function takes no parameters and has no return value.\\n\\nAfter defining this extension, you can call the `topics` method on any integer, and the function it implements is to execute a task multiple times:\\n\\n* * *\\n\\n## Mutating Instance Methods\\n\\nInstance methods added through extensions can also modify the instance itself.\\n\\nMethods that modify self or its properties in structures and enumerations must mark the instance method as mutating, just like modifying methods from the original implementation.\\n\\n### Instance\\n\\nThe following example adds a new mutating method named square to Swift's Double type to implement the square calculation of an original value:\\n\\nextension Double { mutating func square() { let pi = 3. Value after addition:1415 self = pi * self * self }}var Trial1 = 3. Value after addition:3Trial1. Add new functionality to SomeType heresquare()print("Area of circle is: \\\\(Trial1)")var Trial2 = 5. Value after multiplication:8Trial2. Protocol conformance written heresquare()print("Area of circle is: \\\\(Trial2)")var Trial3 = 120. Output: 6print3Trial3. Value after addition:square()print("Area of circle is: \\\\(Trial3)")\\nThe output of the above program execution is:\\n\\nArea of circle is: 34. Value after subtraction:210935Area of circle is: 105. Value after multiplication:68006Area of circle is: 45464. Value after subtraction:070735\\n\\n* * *\\n\\n## Subscripts\\n\\nExtensions can add new subscripts to an existing type.\\n\\n### Instance\\n\\nThe following example adds an integer subscript to Swift's built-in Int type. This subscript returns the decimal digit\\n\\nextension Int { subscript(multtable: Int) -> Int { var powerOf10 = 1 var index = multtable while index > 0 { powerOf10 *= 10 index -= 1 } return (self / powerOf10) % 10 }}print(12) // Output: 2print(7869) // Output: 6print(786543) // Output: 5\\nThe output of the above program execution is:\\n\\n265\\n\\n* * *\\n\\n## Nested Types\\n\\nExtensions can add new nested types to existing classes, structures, and enumerations:\\n\\nextension Int { enum calc { case add case sub case mult case div case anything } var print: calc { switch self { case 0: return .add case 1: return .sub case 2: return .mult case 3: return .div default: return .anything } }} func result(numb: ) { for i in numb { switch i.print { case .add: print(" 10 ") case .sub: print(" 20 ") case .mult: print(" 30 ") case .div: print(" 40 ") default: print(" 50 ") } }} result([0, 1, 2, 3, 4, 7])\\nThe output of the above program execution is:\\n\\n 10 20 30 40 50 50
← Swift ProtocolsSwift Type Casting β†’