简体   繁体   中英

cannot convert value of '()' to expected argument type 'String' swift 3.0

I can't find anything online or on stackoverflow. I'm getting this error Cannot convert value of '()' to expected argument type 'String' when I use the let color. I'm presuming I need to convert () to a String.

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
}
let colors = [
    no0 = "7A9474",
    no1 = "8C4482",
]

I would assume no0 and no1 are String variables elsewhere.

Unfortunately in Swift, the assignment is not a statement , but an expression that returns Void (ie () ) . Thus the compiler won't complain about this declaration, even it certainly looks wrong to the human eye.

The expression no0 = "7A9474" can be viewed as a function that returns () . So the compiler will see an array of two () and infer the type of colors to be [()] .

let color = colors[random]

And thus the type of color is () . (Swift 3 will issue a warning on this line)

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

And thus a type error on this line.


Perhaps you want this instead:

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

no0,no1...those index is already in array.

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 ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM