import Foundation
var dic: [String: Int] = [:]
var arr: [String] = []
while true {
print("请输入一个水果名称(输入exit结束):")
let fruit = readLine() ?? ""
if fruit.lowercased() == "exit" {
break
}
var priceString: String = ""
var p1: Int = 0
repeat {
print("请输入 \(fruit) 的价格(只能包含0~9的数字):")
priceString = readLine() ?? ""
let priceCharacterSet = CharacterSet(charactersIn: "0123456789")
if priceString.rangeOfCharacter(from: priceCharacterSet.inverted) == nil {
if let priceInt = Int(priceString) {
p1 = priceInt
break
} else {
print("转换价格失败,请重新输入。")
}
} else {
print("价格包含非法字符,请重新输入。")
}
} while true
dic[fruit] = p1
}
for (_, value) in dic {
arr.append("\(value)")
}
if !arr.isEmpty {
arr.removeFirst()
}
if let firstElement = arr.first {
print("数组第一个元素是:\(firstElement)")
}
print("字典:\(dic)")
print("数组:\(arr)")