随机数组字符串变为零

时间:2016-03-26 22:12:01

标签: ios arrays xcode swift

我在我的数组字符串中使用random范围函数。另外我使用过滤器不重复我的数组字符串,但有时我的第一个随机字符串是nil。

随机范围代码:

func randomNumber(range: Range<Int> = 1...6) -> Int {
    let min = range.startIndex
    let max = range.endIndex
    return Int(arc4random_uniform(UInt32(max - min))) + min
}

我从firstItem

获得零
var a = cities[randomNumber(0...80)]

if Marmara.contains(a){
    firstItem = a
    print(firstItem) //It's getting nil sometimes.
    var filteredForSecond = Marmara.filter{$0 != firstItem}
    secondItem = filteredForSecond[randomNumber(0...filteredForSecond.count-1)]
    print(secondItem)
    var filteredForThird = Marmara.filter{$0 != secondItem && $0 != firstItem}
    thirdItem = filteredForThird[randomNumber(0...filteredForThird.count-1)]
    print(thirdItem)
    var filteredForFourth = Marmara.filter{$0 != thirdItem && $0 != secondItem && $0 != firstItem}
    print(fourthItem)
    fourthItem = filteredForFourth[randomNumber(0...filteredForFourth.count-1)]
    //sehirler.removeAtIndex(s)

    print("\(firstItem), \(secondItem), \(thirdItem), \(fourthItem)")
}

我使用此代码在数组中有一个“81”字符串。我该怎么做才能解决这个nil字符串问题?

2 个答案:

答案 0 :(得分:1)

我至少会做出以下改变。看看这是否解决了这个问题。

var a = cities[randomNumber(0...cities.count-1)]

答案 1 :(得分:0)

我解决了这个问题。我检查它是否为零,再次取随机字符串并且它不再为零了。

以下是工作代码:

var a = cities[randomNumber(0...cities.count-1)]

while a.isEmpty{
    a = cities[randomNumber(0...cities.count-1)]
}

if Marmara.contains(a) && a != ""{
    firstItem = a
    if firstItem.isEmpty{
        print("nil")
    }
    print(firstItem)
    var filteredForSecond = Marmara.filter{$0 != firstItem}
    secondItem = filteredForSecond[randomNumber(0...filteredForSecond.count-1)]
    print(secondItem)
    var filteredForThird = Marmara.filter{$0 != secondItem && $0 != firstItem}
    thirdItem = filteredForThird[randomNumber(0...filteredForThird.count-1)]
    print(thirdItem)
    var filteredForFourth = Marmara.filter{$0 != thirdItem && $0 != secondItem && $0 != firstItem}
    print(fourthItem)
    fourthItem = filteredForFourth[randomNumber(0...filteredForFourth.count-1)]
    //sehirler.removeAtIndex(s)

    print("\(firstItem), \(secondItem), \(thirdItem), \(fourthItem)")
}