UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

func and count question

Forums > Swift

Good afternoon,

in the below, the code is failing when i enter say last: 15, where i call the function. I thought by using the .count with the if clause it would just print "You have removed too many letters", but it just produces the fatal error below.....appreciate any thoughts

'Fatal error: Can't remove more items from a collection than it contains: file Swift/RangeReplaceableCollection.swift, line 886'

func reedo(input: String, first: Int, last: Int) -> String {
    // we require a variable to manipulate strings
    var newString = input
    newString.removeFirst(first)
    newString.removeLast(last)
    newString.count
    if newString.count > 0 {
        return newString
    }else {
        return "You have removed too many letters"
    }
}

print(reedo(input: "Hello Mum", first: 2, last: 1))

2      

You should check the length (i.e. count) of the String before calling removeFirst and RemoveLast. If the string has only 3 letters and you call .removeLast(5) you'll get a Fatal Error, no matter that you use it on a copy of the input string.

func reedo(input: String, first: Int, last: Int) -> String {
    var newString = input
    if newString.count >= first + last {
        newString.removeFirst(first)
        newString.removeLast(last)
        return newString
    } else {
        return "You have removed too many letters"
    }
}

2      

thanks...really appreciate the feedback. will rewrite the code

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.