您可以严格使用泛型类型,也可以给一个参数多于一种类型吗? [英] Can you Strict Generic types or give one parameter more than one type ?

查看:52
本文介绍了您可以严格使用泛型类型,也可以给一个参数多于一种类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想指定一个可能为IntegerString的类型,并将其用作func中的特殊类型,我尝试了typealias 但是它不能解决这种情况,因为类型别名不能具有or参数,因为它仅使用&,因此请考虑以下情况.

For example i want to specify a type that might be Integer or String and use it as special type in func i tried typealias but it wont solve the case because typealiases can't have or arguments as its only uses & therefore consider the case below.

typealias alis = StringProtocol & Numeric


func foo <T: alis> (vee: T) -> T{
// do something
    return vee
}

我希望此函子接受(IntString)而不是其他任何参数(<T>)的参数类型

i want this func to accept a parameter type of either ( Int or String ) not anything else (<T>),

如您所见,我尝试使用typealias并且没有编译错误.

as you can see i tried with typealias and i have no compile error.

但是,尝试使用该功能将导致这些错误.

however trying to use the function will lead to these errors.

foo(vee: 1) //Argument type 'Int' does not conform to expected type 'StringProtocol'

还有

foo(vee: "v") //Argument type 'String' does not conform to expected type 'Numeric'

这可以迅速实现吗?如果是这样的话.

is this achievable with swift ? if so how.

推荐答案

让我们假设您可以使用OR运算符组合协议,那么对于?

Let's suppose that you could use a OR operator to combine protocols, what would you be able to do with something of type (Int | String)?

并不是所有您可以对Int进行的操作都可以在(Int | String)上完成,因为它可能是一个潜在的字符串.同样,并不是您可以对(Int | String)进行的所有操作都可以在(Int | String)上完成,因为从根本上说,它可能是Int.

Not everything you can do to an Int can be done on (Int | String), because it might be a string underlyingly. Similarly, not everything you can do to an String can be done on (Int | String), because it might be a Int underlyingly.

现在您可能会说:啊.我知道IntString都具有description属性.我应该能够使用类型为(Int | String)的变量访问description."

Now you might say "Ah. I know that Int and String both have a description property. I should be able to access description on a variable of type (Int | String)."

在这种情况下,您可以自己创建一个这样的协议,并且仅使IntString符合该协议:

Well, in that case, you can just create such a protocol yourself and only have Int and String conform to it:

protocol IntOrString {
    var description: String { get }
}

extension Int : IntOrString {}
extension String : IntOrString {}

(请注意,在CustomStringConvertible中已经定义了description.为争辩起见,假设它不存在.)

(Note that description is already defined in CustomStringConvertible. For the sake of argument, imagine that does not exist.)

这篇关于您可以严格使用泛型类型,也可以给一个参数多于一种类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆