Петли для ключевых элементов словаря - PullRequest
0 голосов
/ 06 мая 2018

Как я могу исправить код, чтобы цикл задавал вопрос для каждого из элементов в словаре?

* Отредактировал код, чтобы сделать то, что я пытаюсь сделать, более понятным. Я хочу, чтобы код остановился и дождался ввода перед тем, как перейти к следующему элементу в словаре.

   import Foundation
import UIKit



var squad = [1:"Arsh", 2:"Arbab", 3:"Ayush", 4:"KC", 5:"Jaski", 6:"Gunny", 7:"Harsh", 8:"Nagib", 9:"Rithin", 10:"Gursh", 11:"Sonny"]
let coming = "Yes"

let notComing = "No"

var attendees = [String]()

for ( key , person) in squad {
     // key == 1

//   key = counter

    // repeat {

    print("Are you attending \(person)?")
    let response = readLine()
        print(response as Any)

        if response == coming {
             attendees.append(person)
        }

        else if response == notComing {
            print("Sorry to hear that")
        }

        else {
            print("Invalid Input")
        }


       // }  while key <= 11

        // key += 1
    }




print(attendees)
print(attendees.count)

1 Ответ

0 голосов
/ 09 мая 2018

Чтобы экспериментировать с функциями ввода с клавиатуры, такими как readLine(), создайте проект, выбрав в меню Xcode:

Файл> Создать> Проект> macOS> Инструмент командной строки

и запустите его в Xcode, панель консоли отладки будет работать как терминал. Вот код, который вы ищете:

import Foundation

var squad = [1:"Arsh", 2:"Arbab", 3:"Ayush", 4:"KC", 5:"Jaski", 6:"Gunny", 7:"Harsh", 8:"Nagib", 9:"Rithin", 10:"Gursh", 11:"Sonny"]

let coming = "yes"
let notComing = "no"

var attendees = [String]()
let array = squad.map {return ($0.key, $0.value)} // Turn the dictionary to an array of tuples
let sortedArray = array.sorted(by: {$0.0 < $1.0 }) // Sort the array by the first element of the tuple

// Ask the squad one by one
for ( _ , person) in sortedArray {

    print("Are you attending \(person)?")
    if let response = readLine() {
        //remove white spaces and all letters lowercased so that "Yes", "yes" and "YES" would all be accepted
        if response.lowercased().trimmingCharacters(in: .whitespaces) == coming {
            attendees.append(person)
        }

        else if response.lowercased().trimmingCharacters(in: .whitespaces) == notComing {
            print("Sorry to hear that")
        }

        else {
            print("Invalid Input")
        }
    }
}

print("attendees : \(attendees)")
print("attendees.count = \(attendees.count)")
...