Jason Jason - 1 year ago 76
Swift Question

Removing characters from a string in Swift


I have a function :

func IphoneName() -> String
let device = UIDevice.currentDevice().name
return device

Which returns the name of the iphone (simple). I need to remove the "'s Iphone" from the end. I have been reading about changing it to NSString and use ranges, but I am a bit lost!!
Can you help ?

Answer Source

What about this:

extension String {

    func removeCharsFromEnd(count:Int) -> String{
        let stringLength = countElements(self)

        let substringIndex = (stringLength < count) ? 0 : stringLength - count

        return self.substringToIndex(advance(self.startIndex, substringIndex))

    func length() -> Int {
        return countElements(self)


var deviceName:String = "Mike's Iphone"

let newName = deviceName.removeCharsFromEnd("'s Iphone".length()) // Mike

But if you want replace method use stringByReplacingOccurrencesOfString as @Kirsteins posted:

let newName2 = deviceName.stringByReplacingOccurrencesOfString(
     "'s Iphone", 
     withString: "", 
     options: .allZeros, // or just nil
     range: nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download