WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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

   

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"
    }
}

   

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

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain. The code can be hard to write, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app.

Explore the docs

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

Reply to this topic…

You need to create an account or log in to reply.

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.