Category: swift

Swift is a general-purpose, multi-paradigm, compiled programming language developed by Apple Inc. and the open-source community. First released in 2014, Swift was developed as a replacement for Apple’s earlier programming language Objective-C, as Objective-C had been largely unchanged since the early 1980s and lacked modern language features.

  • 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
  • Subscript in Swift

    Subscript in Swift

    Subscript in Swift

    By implementing Subscript we can set and retrieve structure value by index (associative array or dictionary style) without separate methods for setting and retrieval. Classes and Enumerations can define subscripts too.

    For example, I want to build an Address struct that can hold different string values. A contact can have a present address and a permanent address.

    public struct Address {
        public var presentAddress: String?
        public var permanentAddress: String?
    
        public init() {
    
        }
    }
    
    var address = Address()
    address.presentAddress = "Present Address"
    address.permanentAddress = "Permanent Address"
    
    print(address.presentAddress)
    print(address.permanentAddress)

    Without the subscript the Address has limited two members, presentAddress and permanentAddress. If we implement subscript we can have more than two addresses.

    
    public struct Address {
        private var members: Dictionary<String, String> = [:]
        
        public init() {
        }
        
        public subscript(member: String) -> String {
            get {
                return members[member, default: "No value set"]
            }
            
            set(newValue) {
                members[member] = newValue
            }
        }
    }
    
    var address = Address()
    
    address["presentAddress"] = "Present Address"
    address["permanentAddress"] = "Permanent Address"
    address["officeAddress"] = "Office Address"
    
    print(address["presentAddress"])
    print(address["permanentAddress"])
    print(address["officeAddress"])

    Spread the love