Swift致命错误:数组索引超出范围

时间:2021-06-04 16:46:19

How can I fix this code so I no longer get an error. The error I get is fatal error: Array index out of range. The code checks how many "x" and "o" there are in a string

如何修复此代码,以便我不再收到错误。我得到的错误是致命错误:数组索引超出范围。代码检查字符串中有多少“x”和“o”

var input = "xxxoxoooxoxo"

var inputString = Array(input.characters)

var XString = ""

var OString = ""

for var i = 0; i <= inputString.count; ++i {

    if inputString[i] == "x" {

        XString.append(inputString[i])

    }

    else if inputString[i] == "o" {

        OString.append(inputString[i])

    }

}

if XString.characters.count == OString.characters.count {

    print("equal")

}

else {

    print("Not Equal")

}

Thanks for the help.

谢谢您的帮助。

4 个解决方案

#1


3  

Replace this

替换它

for var i = 0; i <= inputString.count; ++i

with this:

有了这个:

for var i = 0; i < inputString.count; ++i

Arrays are zero indexed. That means the first element has the index 0. The second element has index 1. ... . The last element has the index array.count-1.

数组是零索引的。这意味着第一个元素的索引为0.第二个元素的索引为1. ....最后一个元素的索引是array.count-1。

#2


3  

@dasdom is correct. but here is a more Swift-y way to do it:

@dasdom是对的。但这是一种更快捷的方式:

// input string
var input = "ooooxxxxxxxoxoooxoxo" 

// difference between number of x's and number of o's
var diff = 0 

// perform this function for each character in `input.characters`:
input.characters.forEach {
    switch $0 // $0 is the argument to our function (unnamed)
    {
        case "x": diff += 1          // x's are +1
        case "o": diff -= 1          // o's are -1
        default: fatalError()        // we expect only 'x' or 'o'... if we get something else, just crash
    }
}

// use the ternary (?:) operator to print the answer.
// (<result> = <condition> ? <if-true value> : <if-false value>)
print( diff == 0 ? "equal" : "not equal" )

A shorter version, inspired by @Eendje's answer :)

一个较短的版本,灵感来自@ Eendje的回答:)

print( input.characters.reduce(0) { $0 + [ "x":1, "o":-1 ][ $1 ]! } != 0 ? "not" : "", "equal" )

#3


2  

While everyone is giving you an alternative, I thought this would be a nice addition as well:

虽然每个人都给你一个替代品,但我认为这也是一个很好的补充:

var input = "xxxxxoxoooxoxo"

You can get the count by using filter:

您可以使用过滤器获取计数:

let xCount = input.characters.filter { $0 == "x" }.count
let oCount = input.characters.filter { $0 == "o" }.count

print( xCount == oCount ? "equal" : "not equal" )

In your case, using reduce would be more efficient and it's shorter:

在您的情况下,使用reduce会更有效,而且更短:

let result = input.characters.reduce(0) { $0 + ($1 == "x" ? 1 : -1) }

print(result == 0 ? "equal" : "not equal") // not equal

This is only if you're sure input only contains x and o. If not, then you'll have to change the evaluation to:

仅当您确定输入仅包含x和o时才会这样。如果没有,那么您必须将评估更改为:

{ $0 + ($1 == "x" ? 1 : $1 == "o" ? -1 : 0) }

#4


0  

You are enumerating pass the range of the array. Use this instead.

您枚举传递数组的范围。改用它。

for var i = 0; i < inputString.count; ++i {

Or you can use this more idiomatic code:

或者你可以使用这个更惯用的代码:

var input = "xxxoxoooxoxo"


var xString = 0

var oString = 0

for c in input.characters {

    if c == "x" {

        xString++

    }

    else if c == "o" {

        oString++

    }

}

if oString == xString {

    print("equal")

}

else {

    print("Not Equal")

}

#1


3  

Replace this

替换它

for var i = 0; i <= inputString.count; ++i

with this:

有了这个:

for var i = 0; i < inputString.count; ++i

Arrays are zero indexed. That means the first element has the index 0. The second element has index 1. ... . The last element has the index array.count-1.

数组是零索引的。这意味着第一个元素的索引为0.第二个元素的索引为1. ....最后一个元素的索引是array.count-1。

#2


3  

@dasdom is correct. but here is a more Swift-y way to do it:

@dasdom是对的。但这是一种更快捷的方式:

// input string
var input = "ooooxxxxxxxoxoooxoxo" 

// difference between number of x's and number of o's
var diff = 0 

// perform this function for each character in `input.characters`:
input.characters.forEach {
    switch $0 // $0 is the argument to our function (unnamed)
    {
        case "x": diff += 1          // x's are +1
        case "o": diff -= 1          // o's are -1
        default: fatalError()        // we expect only 'x' or 'o'... if we get something else, just crash
    }
}

// use the ternary (?:) operator to print the answer.
// (<result> = <condition> ? <if-true value> : <if-false value>)
print( diff == 0 ? "equal" : "not equal" )

A shorter version, inspired by @Eendje's answer :)

一个较短的版本,灵感来自@ Eendje的回答:)

print( input.characters.reduce(0) { $0 + [ "x":1, "o":-1 ][ $1 ]! } != 0 ? "not" : "", "equal" )

#3


2  

While everyone is giving you an alternative, I thought this would be a nice addition as well:

虽然每个人都给你一个替代品,但我认为这也是一个很好的补充:

var input = "xxxxxoxoooxoxo"

You can get the count by using filter:

您可以使用过滤器获取计数:

let xCount = input.characters.filter { $0 == "x" }.count
let oCount = input.characters.filter { $0 == "o" }.count

print( xCount == oCount ? "equal" : "not equal" )

In your case, using reduce would be more efficient and it's shorter:

在您的情况下,使用reduce会更有效,而且更短:

let result = input.characters.reduce(0) { $0 + ($1 == "x" ? 1 : -1) }

print(result == 0 ? "equal" : "not equal") // not equal

This is only if you're sure input only contains x and o. If not, then you'll have to change the evaluation to:

仅当您确定输入仅包含x和o时才会这样。如果没有,那么您必须将评估更改为:

{ $0 + ($1 == "x" ? 1 : $1 == "o" ? -1 : 0) }

#4


0  

You are enumerating pass the range of the array. Use this instead.

您枚举传递数组的范围。改用它。

for var i = 0; i < inputString.count; ++i {

Or you can use this more idiomatic code:

或者你可以使用这个更惯用的代码:

var input = "xxxoxoooxoxo"


var xString = 0

var oString = 0

for c in input.characters {

    if c == "x" {

        xString++

    }

    else if c == "o" {

        oString++

    }

}

if oString == xString {

    print("equal")

}

else {

    print("Not Equal")

}