[英]Type Inference in tuples?
let http404Error = (statusCode: 404, statusMessage: "Not found")
print(http404Error.0, http404Error.1)
我對元組有一些問題和“問題”:
問題1:
但是如果我希望statusCode只是一個Int和一個Int呢?
因為“statusCode:Int = 404”似乎不起作用?
問題2:
如果我想縮短“print(http404Error.0,http404Error.1)”部分該怎么辦?
有沒有簡短的方法來編寫它,比如print(http404Error。[0,1])?
謝謝你的幫助 :)
你可以試試
let http404Error:(Int,String) = (statusCode: 404, statusMessage: "Not found")
要指定類型,您可以定義類型別名,如:
typealias HttpStatus = (statusCode: Int, statusMessage: String)
let http404Error = HttpStatus(403, "Not found")
print(http404Error.0, http404Error.1)
為了縮短打印聲明,我認為沒有一種簡單的方法可以做到這一點。 你可以做的一件事是,你可以創建一個自定義函數,它將元組作為參數,格式化值並返回一個字符串。
func getStatus(_ status: HttpStatus) -> String {
return "\(status.statusCode) \(status.statusMessage)"
}
print(getStatus(http404Error))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.