简体   繁体   English

不能使用类型为“UInt32”的索引为 [String] 类型的值添加下标

[英]Cannot subscript a value of type [String] with an index of type “UInt32”

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?有谁知道为什么以及如何解决它?

You should use an Int to access an array by index您应该使用Int按索引访问数组

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))

Swift 4.2 implemented SE-0202: Random Unification Thus there is no need to use the imported C function arc4random(). Swift 4.2 实现了SE-0202:随机统一因此不需要使用导入的 C 函数 arc4random()。 You can now use Swift's own native random API.您现在可以使用 Swift 自己的原生随机 API。 By calling the random() method on any numeric type with the range needed通过对具有所需范围的任何数字类型调用random()方法

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法下标&#39;[UInt32]&#39;类型的值 - Cannot subscript a value of type '[UInt32]' 不能使用类型为“Int”的索引为“[String : String]”类型的值添加下标 - Cannot subscript a value of type '[String : String]' with an index of type 'Int' 无法用索引类型“ String”下标“ [[[String:Any]]””的值 - Cannot subscript a value of type '[[String : Any]]' with an index of type 'String' “无法使用索引类型为&#39;String&#39;的类型为&#39;[String]&#39;的值下标”” - “Cannot Subscript a value of type '[String]' with an index of type 'String' ” 无法用索引类型“ String”下标“ String”类型的值 - Cannot subscript a value of type 'String' with an index of type 'String' 无法使用索引类型为“字符串”的下标类型为[[HTTPCookiePropertyKey:Any]”的值 - Cannot subscript a value of type '[HTTPCookiePropertyKey : Any]' with an index of type 'String' Swift-无法为索引类型为NSNumber的值类型[String]下标吗? - Swift - Cannot subscript a value type [String] with an index type of NSNumber? Swift-无法下标&#39;[Array]类型的值 <String> ]”,索引类型为“ IndexPath” - Swift - Cannot subscript a value of type '[Array<String>]' with an index of type 'IndexPath' 无法用[NSIndexPath]类型的索引下标[String]类型的值-prepareForSegue - Cannot subscript a value of type [String] with an index of type [NSIndexPath] - prepareForSegue 无法使用类型为“字符串”的索引为“[CustomObject]”类型的值添加下标 - Cannot subscript a value of type '[CustomObject]' with an index of type 'String'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM