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!)
            }
        }
    }

Wednesday, February 11, 2015

Alternative of #pragma mark for Swift


In Objective C, you might have used the #pragma mark directive for code organization in Jump bar.
But with Xcode 6 there is no pragma directive. Instead of this, you can use MARK, TODO and FIXME for managing the code which is supported by Xcode 6.

1) MARK:- It is an alternative of #pragma mark directive. It can be used for organizing code in a logical way so that it can be navigated by jump bar.




2) TO DO:- You can use this tag to make reminder to work on this later. You can use this tag within the function or outside the function.




3) FIX ME:- You can use this tag to make a reminder to fix some piece of code or methods. It can be placed inside or outside of the methods.




Note- “-” is optional in all the directives. If you use this dash then it will show a separator line in the Jump bar above the text.

Monday, February 2, 2015

Generic Functions in Swift.


Generic is one of the powerful feature of Swift. Most of the Swift Standard library uses this feature.

For instance, Swift Array and Dictionary are Generics Collection which can hold the value of any Type. You can create the array which holds Int values or String values.

With Generics code, developer can write flexible and reusable function which can work with any Type.

Suppose you have to write a function to swap two Int values. 



In Swift, parameters are passed by value so you can’t change the parameters value within the Function. If you want to modify the parameters value then you have to define the parameters as inout.

When you call a  function with an inout parameters, you use ampersand (&). This is something like passing the address of values as we have in C language.

If you want to write a function which can swap String or Doubles values then your function will look like this.





You may have noticed that all these functions bodies are same. Only difference is the type of the value passed to this functions.

So, you can write Generics functions which can work with any Type.




Generics function uses a placeholder type in angular bracket instead of actual Type name (Int, String). Both parameter a and b must be of same T type whatever T represents.