首页 > 解决方案 > 从字符串中同时获取前 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 没有打印。它变得零。

标签: iosarraysswift

解决方案


你可以试试

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:",")

推荐阅读