如何在Swift中增加开关案例/循环中的变量范围?
如何使用switch case语句来创建在switch case语句之外有效的变量/常量。如果没有办法做到这一点,我还可以做些什么来达到同样的效果,即根据条件创建变量,并使其在“全局”或更高范围内可访问如何在Swift中增加开关案例/循环中的变量范围?,swift,Swift,如何使用switch case语句来创建在switch case语句之外有效的变量/常量。如果没有办法做到这一点,我还可以做些什么来达到同样的效果,即根据条件创建变量,并使其在“全局”或更高范围内可访问 var dogInfo = (3, "Fido") switch dogInfo { case(var age, "wooff"): println("My dog Fido is \(age) years old") case (3, "Fido"): var match
var dogInfo = (3, "Fido")
switch dogInfo {
case(var age, "wooff"):
println("My dog Fido is \(age) years old")
case (3, "Fido"):
var matchtrue = 10 --> 10
matchtrue -->10
default:
"No match"
}
matchtrue --> Error: Use of unresolved identifier 'matchtrue'
我是这样解决的:
var randomNumberOne = 0, randomNumberTwo = 0, randomNumberThree = 0
func chosen (#a: Int, #b: Int) -> (randomNumberOne: Int, randomNumberTwo: Int, randomNumberThree: Int){
if a > 0 {
let count1 = UInt32(stringArray1.count)-1
let randomNumberOne = Int(arc4random_uniform(count1))+1
}
if b > 0 {
let count2 = UInt32(stringArray2.count)-1 Output: 3 (from earlier)
let randomNumberTwo = Int(arc4random_uniform(count2))+1 Output: 2
}
if a > 0 && b > 0 {
let count3 = UInt32(stringArray3.count)-1
let randomNumberThree = Int(arc4random_uniform(count3))+1
}
return (randomNumberOne, randomNumberTwo, randomNumberThree)
}
chosen(a:0,b:1) Output: (.00,.12,.20)
太好了,现在我可以用这个索引到一个数组中了谢谢这里没有魔术。Swift使用块作用域,开关创建一个新的作用域以防止错误,并向程序员显示变量仅在作用域中使用。如果希望在范围之外使用变量,请在switch子句之外声明这些标识符
var dogInfo = (3, "Fido")
var matchtrue:Int = 0 // whatever you'd like it to default to
switch dogInfo {
case(var age, "wooff"):
println("My dog Fido is \(age) years old")
case (3, "Fido"):
matchtrue = 10 --> 10
matchtrue -->10
default:
"No match"
}
matchtrue --> 10
如果
matchtrue
可以包含值或不包含值(如果未初始化),则应使用开关前声明的可选变量:
var matchtrue: Int?
switch dogInfo {
...
case (3, "Fido"):
matchtrue = 10
...
}
if let matchtrue = matchtrue {
// matchtrue contains a non nil value
}
如果要在外部使用,则不能在开关盒内定义变量-这与在代码块中声明变量并从外部访问相同:
if (test == true) {
var x = 10
}
println(x) // << Error: Use of unresolved identifier 'x'
if(test==true){
变量x=10
}
println(x)/这里有一个方法。把这个贴在操场上。您提供一个年龄和名称,不同的大小写标识匹配,并返回一个元组,其中包含匹配文本和匹配值
func dogMatch(age: Int, name: String) -> (Match: String, Value: Int) {
switch (age, name) {
case(age, "wooff"):
println("My dog Fido is \(age) years old")
return ("Match", 1)
case (3, "Fido"):
return ("Match", 10)
default:
return ("No Match", 0)
}
}
dogMatch(3, "Fido").Match
dogMatch(3, "Fido").Value
该解决方案与该问题有何关联?