Swift如何匹配NSRange数组与带@的全名字符串数组?
解决带@提及用户的文本点击匹配问题
问题场景
存在评论字符串:"@Scott Winburn and @Ben Bloodworth and @Alex Gonzalez and @Jerry Anderson"
拥有两个数组:
- 获取带@的全名数组:
["@Scott Winburn", "@Ben Bloodworth", "@Alex Gonzalez", "@Jerry Anderson"],对应方法getMentionContactsFromComment() - 获取每个全名对应的NSRange数组:
[{0, 14}, {19, 15}, {39, 14}, {58, 15}],对应方法setRangedMentionContactValues()
需求
匹配两个数组中的对应项(顺序一致),点击文本对应NSRange范围时,获取去掉@符号的用户名。
尝试过的方法
- 嵌套循环遍历两个数组,但匹配失败,点击时重复输出位置值
- 硬编码NSRange值可实现功能,但无法动态适配
- 遍历NSRange数组可判断点击范围,但无法关联对应用户名
最终解决方案
通过Swift的zip函数将两个数组配对遍历,实现动态匹配,代码如下:
for (mentionName, mentionRange) in zip(getMentionContactsFromComment(), setRangedMentionContactValues()) { if gesture.didTapAttributedTextInLabel(label: parent.label, inRange: mentionRange) { if mentionRange == NSRange(location: mentionRange.location, length: mentionName.count) { let newMentionName = String(mentionName.dropFirst()) print(newMentionName) } } }
内容的提问来源于stack exchange,提问作者Scott W
相关产品推荐
相关产品推荐

