将结构添加到字典中,然后随机调用这些结构
我想在这里做两件不同的事情,并且两者都有错误。我试图将结构添加到字典,然后我写了一个函数,随机抽取一个字典条目。将结构添加到字典中,然后随机调用这些结构
这里的结构:
struct Customer
{
var name: String
var email: String
}
和字典:
var customerDatabase: [String: String] = [Customer(name: "Lionel Messi", email:
"[email protected]"), Customer(name: "Cristiano Ronaldo", email: "[email protected]"),
Customer(name: "Wayne Rooney", email: "[email protected]")]
这里的错误消息我得到的词典:
Playground execution failed: :45:42: error: type '[String : String]' does not conform to protocol 'ArrayLiteralConvertible' var customerDatabase: [String: String] = [Customer(name: "Lionel Messi", email: "[email protected]"), Customer(name: "Cristiano Ronaldo", email: "[email protected]"), Customer(name: "Wayne Rooney", email: "[email protected]")]
最后,我的功能,将从我的字典中随机抽取一个Customer结构体。
func randomCustomer() ->()
{
var customer = arc4random_uniform(customerDatabase)
return customer
}
我的功能的错误消息。
<EXPR>:48:39: error: '[String : String]' is not convertible to 'UInt32'
var customer = arc4random_uniform(customerDatabase)
^
Darwin._:1:5: note: in initialization of parameter '_'
let _: UInt32
对于问这样一个简单的问题,我感觉自己像个小菜鸟。非常感谢您的帮助!
以下是更正代码:
var customerDatabase:[Customer] = [Customer(name: "Lionel Messi", email:
"[email protected]"), Customer(name: "Cristiano Ronaldo", email: "[email protected]"),
Customer(name: "Wayne Rooney", email: "[email protected]")]
func randomCustomer() -> Customer
{
let customer = Int(arc4random_uniform(UInt32(customerDatabase.count)))
return customerDatabase[customer]
}
for _ in 1...10 {
println(randomCustomer().name)
}
1)你真的需要一个数组,而不是一本字典。在这种情况下,您需要一组Customer
对象或[Customer]
。
2)randomCustomer
函数需要返回一个Customer
。首先,请致电arc4random_uniform()
,它会生成0
之间的数字,比您传递的数字少1。在这个例子中,我们将数组中的数量为3的Customer
对象的数量传递给它,但首先我们必须将它转换为UInt32
,因为这是arc4random想要的。它会生成一个随机数0,1或2,并将其作为UInt32
返回,我们将其转回Int
并分配给变量customer
。然后这个customer
值被用作Customer
的数组索引,以选择函数返回的那个值。
3)最后,我添加了一个循环来呼叫randomCustomer()
10次并打印出他们的名字。请注意,我使用的循环索引为_
,而不是像i
或index
这样的变量名称,因为我们不使用该变量,所以我们不给它命名。
这是一本字典版本:
var customerDatabase: [String:String] = ["Lionel Messi":
"[email protected]", "Cristiano Ronaldo": "[email protected]",
"Wayne Rooney": "[email protected]"]
func randomCustomer() -> Customer
{
let keys = customerDatabase.keys.array
let customer = Int(arc4random_uniform(UInt32(keys.count)))
let name = keys[customer]
let email = customerDatabase[name]!
return Customer(name: name, email: email)
}
1)这本字典只使用用户名作为关键字和电子邮件的值。
2)这次,随机函数首先创建一个字典中所有键的数组。然后它会选择一个随机密钥,并使用该密钥来获取电子邮件的值。字典查找总是返回可选的值。我们在这里打开!
。最后,它会根据键(名称)和值(电子邮件)创建一个Customer
对象并返回该对象。
太棒了,这有助于很多。你介意分享你在这个功能中做了什么,以使它发挥作用吗?假装你正在向一个5岁的孩子解释(我是Swift的新手,每个细节都有帮助)。 – giwook 2014-08-31 00:43:44
另外,我看到你在说什么关于使用数组而不是字典。如果我想使用字典,以便将客户的名称用作关键字,那么我将如何实现? – giwook 2014-08-31 00:49:15