我想输入一个数字作为字符串,并使用readLine返回一个String?。然后我想将那个输入的String转换为一个也返回Int?的Int。如果任一可选返回nil,则打印错误;否则,使用Int。以下代码有效,但必须有更好的方法。有什么想法吗?
<form method="POST" enctype="multipart/form-data" ng-submit="submitForm()">
Select File To Upload:<br />
<input type="file" name="st_logo" ng-model="setting.file" />
<br /><br />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
答案 0 :(得分:3)
您可以将readLine
响应和转换展开结合到Int
,并确保数字转换成功转换为单个guard
语句,例如
guard let string = readLine(), let number = Int(string) else {
print("input error")
return
}
// use `number`, which is an `Int`, here
如果你愿意,你可以明显地转动它:
if let string = readLine(), let number = Int(string) {
// use `number`, which is an `Int`, here
} else {
print("input error")
}