Swift Tuple索引使用变量作为索引? [英] Swift Tuple index using a variable as the index?

查看:118
本文介绍了Swift Tuple索引使用变量作为索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用变量作为索引的Swift Tuple索引?
任何人都知道是否可以使用变量作为Swift元组索引的索引。我希望使用随机数从元组中选择和项目。我有随机数作为变量,但无法看到如何使用它作为元组的索引。我已搜索过各个地方

解决方案

确保您选择了正确的数据结构



如果你已经达到需要访问元组成员的点,就像索引一样,你应该查看你的数据结构,看看在这种情况下元组是否真的是你的正确选择。正如MartinR在评论中提到的那样,也许数组可能是更合适的选择,或者如simpleBob所提到的那样,字典。



技术上:是的,元组成员可以是通过索引样式访问



您可以利用运行时内省来访问元组的镜像表示的子代,并在给定索引的情况下选择子值。 / p>

例如,对于所有元素属于同一类型的5元组:

  func getMemberOfFiveTuple< T>(元组:(T,T,T,T,T),atIndex:Int) - > T' {
let children = Mirror(反映:tup).children
保护案例让idx = IntMax(atIndex)
其中idx< children.count else {return nil}

返回子项[children.startIndex.advancedBy(idx)]。值为? T
}

let tup =(10,11,12,13,14)
let idx = 3

if let member = getMemberOfFiveTuple( tup,atIndex:idx){
print(member)
} // 13



<请注意, child.value 的类型是任何,因此我们需要尝试将类型转换回到元组的元素类型。如果您的元组包含不同类型的成员,则在编译时无法知道返回类型,并且您可能必须继续对返回的元素使用类型任何


Swift Tuple index using a variable as the index? Anyone know if it is possible to use a variable as the index for a Swift tuple index. I wish to select and item from a tuple using a random number. I have the random number as a variable but cannot see how to use that as the index for a tuple. I have searched various places already

解决方案

Make sure you've chosen the correct data structure

If you've reached a point where you need to access tuple members as if "indexed", you should probably look over your data structure to see if a tuple is really the right choice for you in this case. As MartinR mentions in a comment, perhaps an array would be a more appropriate choice, or, as mentioned by simpleBob, a dictionary.

Technically: yes, tuple members can be accessed by index-style

You can make use of runtime introspection to access the children of a mirror representation of the tuple, and choose a child value given a supplied index.

E.g., for 5-tuples where all elements are of same type:

func getMemberOfFiveTuple<T>(tuple: (T, T, T, T, T), atIndex: Int) -> T? {
    let children = Mirror(reflecting: tup).children
    guard case let idx = IntMax(atIndex)
        where idx < children.count else { return nil }

    return children[children.startIndex.advancedBy(idx)].value as? T
}

let tup = (10, 11, 12, 13, 14)
let idx = 3

if let member = getMemberOfFiveTuple(tup, atIndex: idx) {
    print(member)
} // 13

Note that the type of child.value is Any, hence we need to perform an attempted type conversion back to the element type of the tuple. In case your tuple contains different-type members, the return type cannot be known at compile time, and you'd probably have to keep using type Any for the returned element.

这篇关于Swift Tuple索引使用变量作为索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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