ios - 从字符串中同时获取前 3 个索引值
问题描述
我有一个字符串,我需要在其中获取前 3 个数字。在数完接下来的 3 个数字之后,我需要获取。
这是代码:
let val = pref.string(forKey: "RemoteData")
print(val) //Optional("23,8,21,1,2,16,17,18,11,23,14,6,8,13,4,21,15,22,1,2,9,16,17,7,18,11,32,14,6,33,23,8,31,21,1,3,2,16,24,17,18,5")
我需要做这样的事情:
let startCount = pref.object(forKey: "startCountValue") as? Int ?? 0
let lstCount = pref.object(forKey: "LastCountValue") as? Int ?? 3
let UnlockId = arrayV[startCount..<lstCount]
我在上面为一个整数数组做了这个。但是在这里我不知道如何从字符串中获取前 3 个值:
23,8,21
我需要这样做let UnlockId = arrayV[startCount..<lstCount]
。
一段时间后,我会将其startCount
增加到 + 3,所以下一次从 4 增加到 6。这样它就会消失。
这里的问题是Optional("23,8,21,1,2,16,17,18,11,23,14,6,8,13,4,21,15,22,1,2,9,16,17,7,18,11,32,14,6,33,23,8,31,21,1,3,2,16,24,17,18,5")
我喜欢从 0 到 3 的前 3 个。使用数组我确实喜欢let UnlockId = arrayV[startCount..<lstCount]
. 但在这种情况下,我怎样才能对我的上述值做同样的事情?
更新代码:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let gameId = gameInfo["game_id"] as? String // its printing correct values
let val = pref.string(forKey: "RemoteData")!
let arr = val.components(separatedBy:",")
let startCount = pref.object(forKey: "startCountValue") as? Int ?? 0
let lstCount = pref.object(forKey: "LastCountValue") as? Int ?? 3
let unlockId = arr[startCount..<lstCount]
if unlockId.contains(gameId!) {
print("its locked")
} else {
print("its not locked")
}
}
在这里崩溃:unlockId.contains(gameId!)
但游戏 ID 没有打印。它变得零。
解决方案
你可以试试
let val = pref.string(forKey: "RemoteData")!
let arr = val.components(separatedBy:",")
let startCount = pref.object(forKey: "startCountValue") as? Int ?? 0
let lstCount = pref.object(forKey: "LastCountValue") as? Int ?? 3
let unlockId = arr[startCount..<lstCount]
// if you need it back to string
let unlockStr = unlockId.joined(separator:",")
推荐阅读
- python - 在 python 环境中,如何从特定版本导入包?
- bindy - 从字段为枚举的 CSV 创建 POJO
- c# - 将视图和控制器放在与 ASP.NET Core Web 应用程序不同的项目中
- javascript - GoogleAppScript TABLE WEB,当它具有日期格式值时,我无法显示表值
- python - 嵌套 for 循环的计算复杂度
- java - JPA 不使用 @Transactional 注释保存选择的结果
- emacs - org-mode 根据子任务 todo 状态更改父 todo 状态
- javascript - Javascript中特定日期的时区名称偏移量
- ios - 如何将泛型(关联类型要求)协议作为委托给任何控制器?
- mongodb - $gt、$lt、$gte、$lte 的索引字段方向是什么?