Swift Tuple index using a variable as the index? -
swift tuple index using variable index? know if possible use variable index swift tuple index. wish select , item tuple using random number. have random number variable cannot see how use index tuple. have searched various places already
make sure you've chosen correct data structure
if you've reached point need access tuple members if "indexed", should on data structure see if tuple right choice in case. martinr mentions in comment, perhaps array more appropriate choice, or, mentioned simplebob, dictionary.
technically: yes, tuple members can accessed index-style
you can make use of runtime introspection access children of mirror representation of tuple, , choose child value given supplied index.
e.g., 5-tuples elements 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) 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 type of child.value
any
, hence need perform attempted type conversion element type of tuple. in case tuple contains different-type members, return type cannot known @ compile time, , you'd have keep using type any
returned element.
Comments
Post a Comment