0

In this example, I am creating a new empty array of Int and I want to add certain characters from the other array into it. Originally, in my characters array I store numbers ["1","","2","","3"] and in this array (I might be doing this completely wrong) I want to iterate through those numbers to produce a newarray which will have these numbers [1,2,3] (essentially removing the spaces in between and making them of type Int)

As far as I understand, I have created a dynamic array i.e. no specific size, but I am getting this error : fatal error: Array index out of range and I am not sure why. Could someone clarify this for me? Thanks

 do{
        var data = try String(contentsOfFile: documentsDirectoryPath as String,
            encoding: NSASCIIStringEncoding)
        print(data)
        let characters = Array(data.characters)
        print(characters)
        var newarray = [Int]()

        for var index = 0; index <= characters.count ; ++index {
            if characters[index] == " " {
                index++
            }
            else{
                newarray[index] = index
            }
        }
        print(newarray)    
    }
    catch{

        print("error")
    }   
}
10
  • Do you know at what line you get this error, did you step through the code? Commented Mar 17, 2016 at 17:49
  • yes its here : newarray[index] = index Commented Mar 17, 2016 at 17:50
  • Your problem is (partly) if characters[index] == " " {index++}. You're incrementing twice if this happens. The for loop already increments the value for you. Also a nicer way of writing the loop would be for index in 0..<characters.count {}. As also pointed out, you should use append to add items to your new array. Commented Mar 17, 2016 at 17:50
  • Are 1, 2, 3 in the output have anything to do with "1", "2", "3" from the input? Would output from ["A", " ", "B", " ", "C"] array be any different? Commented Mar 17, 2016 at 18:19
  • @dasblinkenlight well, I was hoping to convert those "1", "2", "3" into integers hence why i removed the " " in my output. I am only storing numbers in that array but in String type for now. So your ["A", " ", "B", " ", "C"] for this particular scenario would be ["A", "B", "C"] but I want to store only Integers so that wouldn't work in my case Commented Mar 17, 2016 at 18:26

6 Answers 6

2

Seeing from your other comments in this thread it appears you are trying to filter out spaces and commas from a string that may look like "1, 2, 3". Correct me if this is wrong. The completely swifty solution to this is as follows:

do {
    var data = try String(contentsOfFile: documentsDirectoryPath as String, encoding: NSASCIIStringEncoding)
    print(data)

    let newarray = data.characters.filter { Int(String($0)) != nil }.map { Int(String($0))! }    
} catch {
    print("error")
}   

Explanation

filter will return an array of Characters that convert to integers. map will then take that array and then transform each element into an integer. We have to convert the Character to a String type because there is no Int constructor that takes a Character.

Sign up to request clarification or add additional context in comments.

9 Comments

You should also probably just change the filter condition to Int(String($0)) != nil. That way there's no chance of a force unwrapping of nil in the map. This is the correct answer though.
Makes it feel a bit redundant with the same statement in both closures but I see your point. I'll edit it.
Wow the only answer that helped, thank you so much. Although it gave me a slight error, so I used @originaluser2 's suggestion and it worked like a charm
@Slayter may i also ask, if I for example I have a number which is a double for example ["1.2","2","3"], I won't be able to achieve the same logic with the code you have provided am i right? (I mean [1.2,2,3])
As far as I know (someone else can correct this) Swift arrays can only hold one data type. Therefore you would have to make them all Doubles then attempt to convert the integer values to Ints later if you need to.
|
1

You have several issues in your code, most important of which is that your approach is incorrect, because it treats a string as a collection of individual characters, while your problem calls for parsing multi-digit numbers.

A better approach is to split the array on commas, and parse integers from trimmed results, like this:

let data = "12, 23, 345"
print(data)
let newarray = data.characters.split(){$0 == ","}.map{
    Int(String.init($0).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()))!
}
print(newarray) // 12, 23, 345

10 Comments

This is wrong, since he obviously wants to have 0 in places corresponding to spaces.
Thank you, that solved the exception, but thats not really what i am aiming to do. I want to replace the value at a particular index in my new array with the new index. For example in my characters array I have these numbers ["1"," ", "2", " ", "3"'] and i want my newarray to be [1, 2, 3']. The append gave me this output : [0, 1, 2, 3, 4]
@s1ddok You are right, she wants to do similar to what you have described, but instead of 0's, just go to the next position in the array and iterate through blank spaces
@user3395936 then you are doing it absolutely wrong, since you adding indexes into your newarray, not characters. Try append(characters[index])
That's because you didn't specify clearly what you "require".
|
0

This happens because your newarray has no capacity.

Try using append method or create array with capacity like so:

let newarray = [Int](count:charactes.count, repeatedValue: 0).

P.S. Also note that you have mistake in for loop, you should use <instead of <= and hustling with iterator value within the loop is a bad idea, you increment this var twice when you see a space, are you sure that is intended?

And you are using two bad practices in Swift. First of all, you use C-like for-loop which will be removed in Swift 3. Same goes for ++ operators. They will be removed too.

Use for-in and += instead. This will make your code more Swift-ish.

Comments

0

Based on what you told in comments (you want to remove space chars from array and get the new one), you can achieve it like so:

let newarray = characters.filter { $0 != " " }

2 Comments

Your code is giving me this : ["1", ",", "2", ",", "3"]
Well, correct the question then. You told us that you want to remove spaces from array, how would we know that you also don't want to be commas there. If you need to extract only numerical chars from array, then you should state it clearly.
0

Another approach:

First remove all spaces from the String, then convert it to Array:

let trimmedData = data.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
let characters = Array(trimmedData.characters)

Edit: if you just want to keep the numbers:

let validNumbers = "1234567890"
let validSet = NSCharacterSet(charactersInString: validNumbers)
let trimmedData = data.stringByTrimmingCharactersInSet(validSet)
let characters = Array(trimmedData.characters)

1 Comment

unfortunately getting this again ["1", ",", "2", ",", "3"]
0

change this line:

for var index = 0; index <= characters.count ; ++index {

to this one:

for var index = 0; index < characters.count ; ++index {

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.