如何在此Swift for-in示例中打印两个键值对

时间:2022-06-02 07:38:51

This example is from Apple's "A Swift Guide" section demonstrating for-in.

这个例子来自Apple的“A Swift Guide”部分,演示了for-in。

Super newbie question, but how come it's not printing the type variable too? Is it something to do with the scope?

超级新手问题,但是为什么它也不打印类型变量呢?它与范围有关吗?

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
var type: String
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
            type = kind
        }
    }
}
largest
type

3 个解决方案

#1


1  

Initialize type to an empty string first like this:

首先将类型初始化为空字符串,如下所示:

var type: String = ""

#2


0  

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]

var largest = 0
var type : String = ""


for (kind , numbers) in interestingNumbers {
    for num in numbers{
        if num>largest{
            largest=num
            type=kind
        }
    }
} 
println(largest,type)

#3


0  

 var items: [(String, String)] = [
        ("Working life balance", "work_life_balance_icon.png"),
        ("Cutting Down on Alcohol", "cutting_down_alcohol_icon.png"),
        ("Smoking Cessation","smoking_cessation_icon.png"),
        ("Eating a healthy diet","eating_healthy_diet_icon.png"),
        ("Exercise", "exercise_icon.png"),
        ("Loosing Weight","loosing_weight_icon"),
        ("Heart Disease Risk Tracker", "qrisk.png"),
        ("BMI Tracker", "bmi.png")
    ]

println("value \(items[0])")

#1


1  

Initialize type to an empty string first like this:

首先将类型初始化为空字符串,如下所示:

var type: String = ""

#2


0  

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]

var largest = 0
var type : String = ""


for (kind , numbers) in interestingNumbers {
    for num in numbers{
        if num>largest{
            largest=num
            type=kind
        }
    }
} 
println(largest,type)

#3


0  

 var items: [(String, String)] = [
        ("Working life balance", "work_life_balance_icon.png"),
        ("Cutting Down on Alcohol", "cutting_down_alcohol_icon.png"),
        ("Smoking Cessation","smoking_cessation_icon.png"),
        ("Eating a healthy diet","eating_healthy_diet_icon.png"),
        ("Exercise", "exercise_icon.png"),
        ("Loosing Weight","loosing_weight_icon"),
        ("Heart Disease Risk Tracker", "qrisk.png"),
        ("BMI Tracker", "bmi.png")
    ]

println("value \(items[0])")