Swift - Using Extensions to extend String

Introduction

Extensions in Swift adds additional functionalities such as methods to an existing class.

Extending Methods

Consider the following example:

extension String {
     func getLatLng(splitter:String) -> (Double, Double) {
         var latlng = self.componentsSeparatedByString(splitter)
         return ((latlng [0] as NSString).doubleValue, (latlng [1] as NSString).doubleValue)
     }
}

The preceding code extends the String class with a method named getLatLng().

It takes in a string containing a latitude and longitude with a separator in between, and returns a tuple containing the latitude and longitude in Double format.

To use the extension method, call it whenever you are dealing with a String variable or constant:

Demo

var str = "1.23456,123.345678"
var latlng  = str.getLatLng (",")
print(latlng.0)//  ww w  . j av  a 2s .  c  om
print(latlng.1)

Related Topic