2014-09-21 46 views
4

如何使用创建switch-case语句外有效的变量/常量的switch case语句。如果没有办法做到这一点,我还能做些什么来实现相同的效果,即创建受条件约束的变量,并使其在“全局”或更高范围内可访问?如何在Swift中增加switch-case/loops中的变量范围?

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) 

现在太好了,我可以用这个指数到一个数组中! 谢谢!

+1

该解决方案如何与问题相关? – mcfedr 2014-11-05 15:52:27

回答

6

这里没有魔术技巧。 Swift使用模块范围,switch创建一个新的范围来防止错误并向程序员显示变量仅在范围中使用。如果你想使用范围之外的变量 - 在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 
3

如果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' 
1

这是一种方法。将其粘贴在操场上。你提供一个年龄和一个名字,不同的例子标识一个匹配并返回一个包含匹配文本和匹配值的元组。

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