Tuesday, February 24, 2015

Subscript in Swift

Subscript are the shortcut to access the elements from collection, sequence and list. You can define the subscript in Class, Struct and enumeration to set and get the value by index. By using Subscript, you don’t need to write the separate methods for getting and setting the values.


Subscript can  read- write or read only. You define subscript by using the subscript keyword and specify one or more input parameters and return type.

subscript(parameters) -> ReturnType {
    get {
        //return someValue
    }
    set (newValue) {
        //setSomeValue()
    }
}

For read only Subscript, you can drop the get keyword.

subscript(parameters) -> ReturnType {
        //return someValue
}

Here, we have created the subscript in String Extension to check the substring is found in String or not. This Subscript will return a true value if substring is found in the String. This is the Read Only subscript.

extension String {
    
    subscript(pattern: String) -> Bool {
            let range = self.rangeOfString(pattern)
            return (range != nil)
    }
}

   var str = "Hello Swift"
   println(str["Swift"]) // true


Let’s create another Subscript of Read-Write type. In this Subscript, we can replace the Substring with another substring. Also, you can check that String contains substring or not. If the String contains the Substring, it will return the substring otherwise nil.

extension String {
    
    subscript(pattern: String) -> String? {
        get {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                return pattern
            } else {
                return nil
            }
        }
        set(replacement) {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                self = self.stringByReplacingCharactersInRange(range!, withString: replacement!)
            }
        }
    }
}


var str = "Hello Swift"
println(str["Swift"]) // Swift
println(str["Java"]) // nil

// Replace Hello with Hi
str["Hello"] = "Hi"
println(str)

In the setter, you can use the newValue keyword in place of replacement and code look like this.

subscript(pattern: String) -> String? {
        get {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                return pattern
            } else {
                return nil
            }
        }
        set {
            let range = self.rangeOfString(pattern)
            
            if range != nil {
                self = self.stringByReplacingCharactersInRange(range!, withString: newValue!)
            }
        }
    }

No comments:

Post a Comment