可选vs绑定值从数组分配var [英] Optional vs Bound value assigning var from array

查看:67
本文介绍了可选vs绑定值从数组分配var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查数组中是否有值,是否使用if-left语句将其分配给String:

I want to check if there is a value in a array and if so assign to a String using a if-left statement:

if let scoreValue = scoreValueArray[element!]{
               // do something with scoreValue 
            }

错误:条件绑定中的绑定值必须为可选类型

Error: Bound value in a conditional binding must be of optional type

因此尝试更改了!到 ?但是错误仍然存​​在.

So tried changing the ! to ? but error persists.

任何输入表示赞赏.

scoreValueArray是一个字符串数组,如果满足条件,则将String值附加到数组,然后将数组保存到NSUserdefaults.

scoreValueArray is an array of strings, where a String value is appended to array if a condition is met, then array is saved to NSUserdefaults.

所以element是一个int,它对应于数组中的索引,只有在索引被String占用的情况下才是bt,所以

So element is a int which corresponds to a index in the array, bt only if the index is occupied with a String, so

scoreValueArray[element!]

可能会返回索引超出范围",因此要使用if-let.

could return an 'Index out of bounds', hence want to use the if-let.

推荐答案

目前尚不清楚您的scoreValueArray是什么类型,但是为了这个答案,我将假定它是Int的数组.

It's not clear what type your scoreValueArray is, but for the sake of this answer, I'm going to assume it's an array of Int.

var scoreValueArray: Array<Int>

现在,如果我们查看Array结构的定义,就会发现:

Now, if we look the definition of the Array struct, we'll find this:

struct Array<T> : MutableCollectionType, Sliceable {
    // other stuff...

    subscript (index: Int) -> T

    // more stuff
}

因此,在数组上调用subscript方法(这就是我们说scoreValueArray时所做的事情)将返回非可选的.并且非可选字符不能用于条件绑定if let/if var语句中.

So, calling the subscript method on our array (which is what we do when we say scoreValueArray) returns a non-optional. And non-optionals cannot be used in the conditional binding if let/if var statements.

我们可以在一个更简单的示例中复制此错误消息:

We can duplicate this error message in a more simple example:

let foo: Int = 3

if let bar = foo {
    // same error
}

这将产生相同的错误.如果我们改为执行类似以下的操作,则可以避免该错误:

This produces the same error. If we instead do something more like the following, we can avoid the error:

let foo: Int? = 3

if let bar = foo {
    // perfectly valid
}

这与字典不同,字典的字典的subscript方法确实返回可选的(T?).如果找到下标中传递的键,则字典将返回一个值;如果所传递的键没有值,则字典将返回nil.

This is different from a dictionary, whose subscript method does return an optional (T?). A dictionary will return a value if the key passed in the subscript is found or nil if there is no value for the passed key.

我们必须像往常一样通过检查数组的长度来避免array-index-out-of-bounds异常:

We must avoid array-index-out-of-bounds exceptions in the same way we always do... by checking the array's length:

if element < scoreValueArray.count {
    scoreValue = scoreValueArray[element]
}

这篇关于可选vs绑定值从数组分配var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆