2016-10-01 32 views
1

我在網上或在stackoverflow上找不到任何東西。 當我使用let顏色時,出現此錯誤Cannot convert value of '()' to expected argument type 'String'。我假設我需要將()轉換爲String。無法將'()'的值轉換爲預期的參數類型'String'swift 3.0

func Change() { 
    print("CALL") 
    let colors = [ 
     no0 = "7A9474", 
     no1 = "8C4482", 
    ] 
    let random = Int(arc4random_uniform(UInt32(colors.count))) 
    let color = colors[random] 
    if random == current { 
     print("FUNNY") 
     Change() 
    } 

    current = random 
    Change2(hex: color, number: String(random)) //HERE IS THE ERROR 
} 
+1

您的'let colors = [no0 = ...'代碼不是有效的Swift語法。這實際上是你的代碼? – jtbandes

+0

我已經在發佈的代碼之外定義了變量。 –

+0

Swift不像其他語言,其中賦值表達式'(no0 = ...)'實際上評估爲賦值。這只是一個Void表達。 – jtbandes

回答

3
let colors = [ 
    no0 = "7A9474", 
    no1 = "8C4482", 
] 

我會假設no0no1在別處字符串變量。

不幸在Swift中,assignment is not a statement, but an expression that returns Void (i.e. ())。因此編譯器不會抱怨這個聲明,即使它看起來對人眼來說也是錯誤的。

可將表達式no0 = "7A9474"視爲返回()的函數。所以編譯器會看到兩個()的數組,並將colors的類型推斷爲[()]

let color = colors[random] 

並且因此color類型是()。 (Swift 3將在這一行上發出警告)

Change2(hex: color, number: String(random)) 
//   ^^^^^ 

因此,這條線上的類型錯誤。


也許你想這個代替:

no0 = "7A9474" 
no1 = "8C4482" 
let colors = [no0, no1] 
+0

有沒有辦法解決這個問題? –

+0

@MaxKrissigo查看更新。 – kennytm

+0

@MaxKrissigo目前尚不清楚你想要做什麼。你想要數組包含什麼? 'no0'和'no1'是什麼? – jtbandes

0

NO0,NO1 ......這些指標已經在數組中。

var current = 0 
func Change() { 
    print("CALL") 
    let colors = ["7A9474","8C4482"] 

    let random = Int(arc4random_uniform(UInt32(colors.count))) 
    let color = colors[random] 
    if random == current { 
     print("FUNNY") 
     Change() 
    } 

    current = random 
    Change2(hex: color, number: String(random)) 
} 

func Change2(hex:String , number:String) { 
    //do ... 
} 
相關問題