For Loop in Apple Swift

前端 未结 5 2059
眼角桃花
眼角桃花 2021-02-14 03:24

Apple\'s newly released language Swift has an example on the official documentation. Example is like this;

let interestingNumbers = [
    \"Prime\": [2, 3, 5, 7,         


        
5条回答
  •  面向向阳花
    2021-02-14 03:47

    for (kind, numbers) in interestingNumbers{}
    

    This for loop actually enumerating the key/value pairs of dictionary interestingNumbers. Where kind is the key and numbers is the correspoding value

    kind:Prime       //Key
    numbers: [2, 3, 5, 7, 11, 13] //Value  
    

    Here the complete solution of the exercise

    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
    

提交回复
热议问题