Swift 4 Tutorial : Split and Join a String

Swift 4 split and join a String :

Sometimes we need to change one part of a string . Suppose you have three different types of url for your image : ”http://mysite.com/image/myimage.jpg” for default size, ”http://mysite.com/image/myimage_h360_w360.jpg” for “360360” sized image and ”http://mysite.com/image/myimage_h100_w100.jpg” for “100100” sized image. You have access only to the first url and you will have to change it like second and third url. How to do that ?

Spliting a string in Swift 4:

To solve the above problem, we can split one string and modify it like whatever we want. For example, if we split “Hello World” by a space (” ”), it will be divided in to two parts “Hello” and “World”. In swift, we can use “string.components(separatedBy: “tag”)” to split a string by “tag”. For the above string, ”http://mysite.com/image/myimage.jpg”, we will split it by “.jpg”. ‘components()’ method returns two strings in an array. If we use “.jpg” as a separator, it will return two strings : ”http://mysite.com/image/myimage” and ” “. Second string is an empty string. Now we can easily modify it to whatever we want.

Creating a Utility class :

To handle the spliting, we can create one Utility class like below :

var url = "http://mysite.com/image/myimage.jpg"

print ("url \(url)")

let largeImageUrl = URLConverter.convertUrl(url:url , size: .large)
print ("Large url : \(largeImageUrl)")

let smallImageUrl = URLConverter.convertUrl(url:url , size: .small)
print ("Large url : \(smallImageUrl)")

enum Size{
    case large
    case small
}

class URLConverter{
    
    static func convertUrl(url: String , size: Size) -> String{
        let splitUrl = url.components(separatedBy: ".jpg")
        
        switch size{
        case .large:
            return "\(splitUrl[0])\("_h360_w360")\(".jpg")"
        case .small:
            return "\(splitUrl[0])\("_h100_w100")\(".jpg")"
        }
    }
}

So, basically we have one utility class ‘URLConverter’ with a function convertUrl(url: String , size: Size) , that splits the url using ‘components()’ method and returns the modified url . It will print the below output :

url http://mysite.com/image/myimage.jpg
Large url : http://mysite.com/image/myimage_h360_w360.jpg
Large url : http://mysite.com/image/myimage_h100_w100.jpg