我正在尝试编写一个函数来从控制台读取矩阵,然后旋转它,但遇到错误:条件绑定的初始化程序必须具有可选类型,而不是“[Int]”
我尝试用 .map 、 .flatMap 替换它,但一切都保持不变
func readMatrix() {
print("Enter matrix dimensions (n m):")
guard let sizeInput = readLine(),
let sizes = sizeInput.split(separator: " ").compactMap({ Int($0) }), // error
sizes.count == 2,
let n = sizes.first,
let m = sizes.last,
n > 0, m > 0 else {
print("Incorrect input of matrix dimensions")
return
}
正如错误告诉您的那样,相关行上没有任何内容返回
Optional
,因此它不能成为 guard let
语句的一部分。
由于
readLine()
does 返回 Optional
,如果您将第一个和第二个语句结合起来,那么您将得到一个在 Optional
语句中工作的 guard let
:
func readMatrix() {
print("Enter matrix dimensions (n m):")
guard let sizes = readLine()?.split(separator: " ").compactMap({ Int($0) }), // <-- Here
sizes.count == 2,
let n = sizes.first,
let m = sizes.last,
n > 0, m > 0 else {
print("Incorrect input of matrix dimensions")
return
}
}
另一种选择是将检查分成两个单独的
guard
语句,let sizes
位于两者之间的单独一行。