简体   繁体   English

元组中的类型推断?

[英]Type Inference in tuples?

let http404Error = (statusCode: 404, statusMessage: "Not found")
print(http404Error.0, http404Error.1)

I got some questions and "problems" with tuples: 我对元组有一些问题和“问题”:

Question 1: 问题1:
But what if I want the statusCode to be an Int and an Int only? 但是如果我希望statusCode只是一个Int和一个Int呢?
Because "statusCode: Int = 404" doesn´t seem to work? 因为“statusCode:Int = 404”似乎不起作用?

Question 2: 问题2:
What if I want to shorten the part "print(http404Error.0, http404Error.1)? 如果我想缩短“print(http404Error.0,http404Error.1)”部分该怎么办?
Is there a short way to write it, something like print(http404Error.[0, 1])? 有没有简短的方法来编写它,比如print(http404Error。[0,1])?

Thanks for your help :) 谢谢你的帮助 :)

你可以试试

let http404Error:(Int,String) = (statusCode: 404, statusMessage: "Not found")

For specifying the type, you can define a type alias like: 要指定类型,您可以定义类型别名,如:

typealias HttpStatus = (statusCode: Int, statusMessage: String)
let http404Error     = HttpStatus(403, "Not found")
print(http404Error.0, http404Error.1)

For shortening the print statement, I don't think there is an easy way to do that. 为了缩短打印声明,我认为没有一种简单的方法可以做到这一点。 One thing you can do is, you can create a custom function which takes the tuple as argument, formats the values and returns a string. 你可以做的一件事是,你可以创建一个自定义函数,它将元组作为参数,格式化值并返回一个字符串。

func getStatus(_ status: HttpStatus) -> String {
    return "\(status.statusCode) \(status.statusMessage)"
}

print(getStatus(http404Error))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM