在Swift中创建数组时为什么会出现错误? [英] Why do I get an error when creating an array in Swift?
问题描述
在我的程序中,我有一个带有一些值的数组:
In my program I have an array with some values:
let pointArray = [
[[185,350],8],
[[248.142766340927,337.440122864078],5],
[[301.67261889578,301.67261889578],5],
[[337.440122864078,248.142766340927],5],
[[350,185],8],
[[327.371274561396,101.60083825503],5],
[[301.67261889578,68.3273811042197],5],
[[248.142766340927,32.5598771359224],5],
[[185,20],8],
[[101.60083825503,42.6287254386042],5],
[[68.3273811042197,68.3273811042197],5],
[[42.6287254386042,101.60083825503],5],
[[20,185],8],
[[32.5598771359224,248.142766340927],5],
[[68.3273811042197,301.67261889578],8],
[[101.60083825503,327.371274561396],5]
]
编译时出现以下错误:
表达过于复杂,无法在合理的时间内解决;考虑将表达式分成不同的子表达式
Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions
为什么会出现错误?仅仅是因为数组太大了吗?
Why am I getting the error? Is it just because the array is too large?
推荐答案
Swift编译器通常不满意,如果您给它一个大数组而不告诉它类型.它必须解析所有这些数据以尝试推断类型.如果声明数组的类型,它将起作用:
The Swift compiler is generally not happy if you give it a big array without telling it the type. It has to parse all of that data to try to infer a type. It will work if you declare the type of the array:
let pointArray:[[Any]] = [[[185,350],8],[[248.142766340927, ...
但是,您必须强制转换以读取值.您应该真正考虑将值放入结构中,并让数组保留该值.
But, you'll have to cast to read the values. You should really consider putting your values into a struct and letting the array hold that.
对于您的数据,元组数组也可以很好地工作:
For your data, an array of tuples might also work nicely:
let pointArray:[(point: [Double], count: Int)] = [
([185,350],8),
([248.142766340927,337.440122864078],5),
([301.67261889578,301.67261889578],5)
]
let point = pointArray[0].point // [185, 350]
let count = pointArray[0].count // 8
这篇关于在Swift中创建数组时为什么会出现错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!