简体   繁体   English

具有泛型参数类型的Swift函数

[英]Swift function with generic argument type

I'm looking for an easy and convenient way to implement a function that accepts all types that can be casted to strings eg: myFunc("This string") or myFunc(2) or myFunc(true) . 我正在寻找一种简单方便的方法来实现一个函数,该函数接受所有可以转换为字符串的类型,例如: myFunc("This string")myFunc(2)myFunc(true) I thought this must be possible with generic parameters and tried something like this: 我认为必须使用通用参数,并尝试这样的事情:

func myFunc<T: StringLiteralConvertible>(param: T? = nil) -> String {
   // ...
   return "\(param)"
}

but I had no success so far. 但到目前为止我没有成功。

Use CustomStringConvertible , not StringLiteralConvertible : 使用CustomStringConvertible ,而不是StringLiteralConvertible

func myFunc<T: CustomStringConvertible>(param: T? = nil) -> String {
    // ...
    return "\(param)"
}

myFunc("Grimxn") // Optional("Grimxn")
myFunc(12) // Optional(12)
myFunc(true) // Optional(true)
myFunc(-1.234) // Optional(-1.234)
//myFunc() // doesn't work. Compiler can't infer T

These will give Optionals because you are casting them to T? 这些会给出Optionals因为你将它们投射到T? to allow your nil default. 允许你的nil默认值。 Drop the default (it doesn't work anyway - nil can't imply T ) to get rid of the Optional . 删除默认值(它无论如何都不起作用 - nil不能暗示T )去除Optional

func myFunc<T: CustomStringConvertible>(param: T) -> String {
    // ...
    return "\(param)"
}

myFunc("Grimxn") // "Grimxn"
myFunc(12) // "12"
myFunc(true) // "true"
myFunc(-1.234) // "-1.234"
//myFunc((1,2)) // doesn't compile
myFunc(NSDate()) // "2015-10-26 10:44:49 +0000"

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

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