在编写Swift的UI来描述用户输入的信息并将信息写入数组时,“ getCommand()”函数与“ readLine()”一起使用!语句返回错误“线程1:致命错误:在展开可选值时意外发现nil”我不知道如何使用可选绑定对其进行修复。
import Foundation
struct StatsVC {
var data = [String : Stats]()
var current = ""
func getCommand() -> [String] {
print("Command" , terminator : "...")
return splitStrPar(readLine()!) //the troublemaker
}
mutating func runStats() {
print("Hello, Welcome to the Krantz UI! Please enter your stats: ")
var command = getCommand()
var infoData: [Stats] = []
while(command[0] != "quit") {
switch command[0] {
case "current" : //code not important here, deleted other options for simplicity
default : print("I don't have that command in my system")
}
command = getCommand()
if(command[0] == "quit") {
print("Krantz Laboratories Thanks You For a Productive Session")
}
}
}
}
//statsVC.swift
func splitStrPar(_ expression: String) -> [String]{
return expression.split{$0 == " "}.map{ String($0) }
}
func splitStrLin(_ expression: String) -> [String]{
return expression.split{$0 == "\n"}.map{ String($0) }
}
//stats.swift
import Foundation
struct Stats {
var values: [Double]
init(values: [Double]){
self.values = values
}
//other functions not important here
}
//main.swift
var vc = StatsVC()
vc.runStats()
答案 0 :(得分:2)
将结构代码更改为以下内容,以正确处理可选包装。使用强制的可选包装后缀运算符!
的做法不佳。我还自由地通过commands数组修改了迭代,以更好地完成我认为您想做的事情。
struct StatsVC {
var data = [String : Stats]()
var current = ""
func getCommands() -> [String] {
print("Command" , terminator : "...")
guard let line = readLine() else { return [] }
return splitStrPar(line)
}
mutating func runStats() {
print("Hello, Welcome to the Krantz CLI! Please enter your stats: ")
let commands = getCommands()
var infoData: [Stats] = []
for command in commands {
switch command {
case "current" :
break //code not important here, deleted other options for simplicity
case "quit":
print("Krantz Laboratories Thanks You For a Productive Session")
return
default :
print("I don't have that command in my system")
}
}
}
}