Month: November 2022

  • Generic in Swift

    Generic in Swift

    Generic in Swift

    In the Swift programming language, the term “generic” refers to a type or function that can work with any type, rather than being tied to a specific type. This allows for greater flexibility and code reuse. For example, a generic function can be written to sort an array of any type, rather than having to write a separate sorting function for each type of array. Using generics can make your code more concise and easy to read, and can help you avoid code duplication.

    Here is an example of a generic function in Swift that sorts an array of elements:

    func sortArray<T: Comparable>(array: [T]) -> [T] {
        let sortedArray = array.sorted()
        return sortedArray
    }
    

    In this example, the sortArray function is a generic function that can sort an array of any type that conforms to the Comparable protocol. This means that the function can sort arrays of integers, strings, or any other type that can be compared using the < and > operators.

    Here is how you could use this function to sort an array of integers:

    let numbers = [10, -1, 3, 9, 2]
    let sortedNumbers = sortArray(array: numbers)
    

    The sortedNumbers constant would be equal to [-1, 2, 3, 9, 10] after this code is executed.

    Spread the love
  • Extensions in Swift

    Extensions in Swift

    Extensions in Swift

    In Swift, an extension is a way to add new functionality to an existing class, structure, enumeration, or protocol type. This can include adding new methods, computed properties, and initializers, as well as providing new implementations of existing methods, properties, and subscripts. Extensions can be used to extend the functionality of any type, including built-in types, user-defined types, and even types defined in other libraries or frameworks.

    Here is an example of using an extension in Swift to add new functionality to an existing type:

    // Define a new Int type that represents a number of seconds
    typealias Seconds = Int
    
    // Define an extension on the Int type to add a new computed property
    extension Int {
        var minutes: Seconds {
            return self * 60
        }
    }
    
    // Use the new property to convert seconds to minutes
    let sixtySeconds = 1.minutes
    print(sixtySeconds)  // Output: 60
    

    In this example, we define a new typealias called Seconds to represent a number of seconds. We then define an extension on the Int type to add a new computed property called minutes. This property returns the number of seconds converted to minutes by multiplying the number of seconds by 60. Finally, we use the new minutes property to convert 1 second to minutes and print the result.

    Learn More

    Spread the love