2014-09-21 28 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