[英]Creating array from random dictionary key values
I want to make a function which returns array of strings and function parameter is array size.我想做一个返回字符串数组的 function 和 function 参数是数组大小。 Array values are random strings from dictionary keys.
数组值是字典键中的随机字符串。 I made this code
我做了这个代码
import UIKit
var cards: [String:Int] = [
"crvenaSedmica":0,
"crvenaOsmica":0,
"crvenaDevetka":0,
"crvenaDesetka":0,
"crvenaDecko":0,
"crvenaDama":0,
"crvenaKralj":0,
"crvenaAs":0,
"bundevaSedmica":0,
"bundevaOsmica":0,
"bundevaDevetka":0,
"bundevaDesetka":0,
"bundevaDecko":0,
"bundevaDama":0,
"bundevaKralj":0,
"bundevaAs":0,
"zelenaSedmica":0,
"zelenaOsmica":0,
"zelenaDevetka":0,
"zelenaDesetka":0,
"zelenaDecko":0,
"zelenaDama":0,
"zelenaKralj":0,
"zelenaAs":0,
"zirSedmica":0,
"zirOsmica":0,
"zirDevetka":0,
"zirDesetka":0,
"zirDecko":0,
"zirDama":0,
"zirKralj":0,
"zirAs":0,
]
func createRandomCards(number:Int) -> [String] {
let cardTypes = Array(cards.keys)
var randomCards: [String] = []
for i in 0..<number {
randomCards[i] = cardTypes[Int.random(in: 0..<32)]
}
return randomCards
}
createRandomCards(number: 5)
but I'm getting:但我得到:
Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0 error.
执行被中断,原因:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0 error。
The real error is actually:真正的错误实际上是:
Swift/ContiguousArrayBuffer.swift:593: Fatal error: Index out of range 2021-05-16 09:59:14.866263-0700 YOURAPPNAME[2540:97613] Swift/ContiguousArrayBuffer.swift:593: Fatal error: Index out of range
Swift/ContiguousArrayBuffer.swift:593: Fatal error: Index out of range 2021-05-16 09:59:14.866263-0700 YOURAPPNAME[2540:97613] Swift/ContiguousArrayBuffer.swift:593: Fatal error: Index out of range
The problem is that you are accessing randomCards
by index, but the element doesn't exist yet.问题是您正在按索引访问
randomCards
,但该元素尚不存在。
var randomCards: [String] = []
...
randomCards[i] = cardTypes[Int.random(in: 0..<32)]
^ right here!
Here, randomCards
is still empty.在这里,
randomCards
仍然是空的。 randomCards[0]
, randomCards[1]
, randomCards[2]
, etc all wouldn't work. randomCards[0]
、 randomCards[1]
、 randomCards[2]
等都不起作用。
Instead, you want to append
.相反,您想要
append
。 Accessing by index is only for when you want to modify an existing element.按索引访问仅适用于您要修改现有元素时。
randomCards.append(cardTypes[Int.random(in: 0..<32)])
Also you are throwing away the function's return value.此外,您正在丢弃函数的返回值。 Instead of...
代替...
createRandomCards(number: 5)
... you should assign it to a constant. ...您应该将其分配给常量。
let cards = createRandomCards(number: 5)
Do not use that for loop.不要使用那个 for 循环。 It has been abstracted away into the
map
method.它已被抽象为
map
方法。 Writing it yourself is error-prone, as you've seen.如您所见,自己编写很容易出错。
Also, do not hard-code the keys' count.此外,不要对键的计数进行硬编码。
func createRandomCards(number: Int) -> [String] {
AnyIterator { }
.prefix(number)
.map { cards.keys.randomElement()! }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.