Cannot subscript a value of type [String] with an

2020-02-07 04:29发布

i've been trying to create a code to generate random names. Here it is

import UIKit

 let arrayOfNames: [String] = ["Giovanni", "Simone", "Francesco", "Ahmet",       "Valerio", "Federico"]

 let arrayOfsNames: [String] = [" İl Genio", " Lo scemo", " Verga", " Fermi", " Medici", " L'assasino"]

 var casual1 = arc4random_uniform(7)
 var casual2 = arc4random_uniform(7)

 let name = "\(arrayOfNames[casual1]) + \(arrayOfsNames[casual2])"

  name

however on the "let name" line it gives me the mistake on the title. Does anyone know why and how to solve it?

2条回答
ゆ 、 Hurt°
2楼-- · 2020-02-07 04:42

Swift 4.2 implemented SE-0202: Random Unification Thus there is no need to use the imported C function arc4random(). You can now use Swift’s own native random API. By calling the random() method on any numeric type with the range needed

Thus

 var casual1 = arc4random_uniform(7)
 var casual2 = arc4random_uniform(7)

should be written as.

var casual1 = Int.random(in: arrayOfNames.indices)
var casual2 = Int.random(in: arrayOfsNames.indices)
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-07 04:51

You should use an Int to access an array by index

Replace this

var casual1 = arc4random_uniform(7)
var casual2 = arc4random_uniform(7)

with this

var casual1 = Int(arc4random_uniform(7))
var casual2 = Int(arc4random_uniform(7))
查看更多
登录 后发表回答