2014-08-31 29 views
0

我想在這裏做兩件不同的事情,並且兩者都有錯誤。我試圖將結構添加到字典,然後我寫了一個函數,隨機抽取一個字典條目。將結構添加到字典中,然後隨機調用這些結構

這裏的結構:

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 

對於問這樣一個簡單的問題,我感覺自己像個小菜鳥。非常感謝您的幫助!

回答

2

以下是更正代碼:

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次並打印出他們的名字。請注意,我使用的循環索引爲_,而不是像iindex這樣的變量名稱,因爲我們不使用該變量,所以我們不給它命名。


這是一本字典版本:

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對象並返回該對象。

+0

太棒了,這有助於很多。你介意分享你在這個功能中做了什麼,以使它發揮作用嗎?假裝你正在向一個5歲的孩子解釋(我是Swift的新手,每個細節都有幫助)。 – giwook 2014-08-31 00:43:44

+0

另外,我看到你在說什麼關於使用數組而不是字典。如果我想使用字典,以便將客戶的名稱用作關鍵字,那麼我將如何實現? – giwook 2014-08-31 00:49:15