我可以在 Swift 中扩展元组吗? [英] Can I extend Tuples in Swift?

查看:39
本文介绍了我可以在 Swift 中扩展元组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Swift 中为(例如)两个值的元组编写一个扩展.例如,我想编写这个 swap 方法:

I'd like to write an extension for tuples of (e.g.) two value in Swift. For instance, I'd like to write this swap method:

let t = (1, "one")
let s = t.swap

这样 s 将是 (String, Int) 类型,值为 ("one", 1).(我知道我可以很容易地实现一个 swap(t) 函数,但这不是我感兴趣的.)

such that s would be of type (String, Int) with value ("one", 1). (I know I can very easily implement a swap(t) function instead, but that's not what I'm interested in.)

我可以这样做吗?我似乎无法在 extension 声明中写出正确的类型名称.

Can I do this? I cannot seem to write the proper type name in the extension declaration.

另外,我想答案是一样的,我可以让一个 2 元组采用给定的协议吗?

Additionally, and I suppose the answer is the same, can I make a 2-tuple adopt a given protocol?

推荐答案

您不能在 Swift 中扩展元组类型.根据类型,有命名类型(其中可以扩展)和复合类型.元组和函数是复合的类型.

You cannot extend tuple types in Swift. According to Types, there are named types (which can be extended) and compound types. Tuples and functions are compound types.

另见(强调):

扩展
扩展为现有功能添加新功能类、结构或枚举类型.

这篇关于我可以在 Swift 中扩展元组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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