美文网首页Swift
swift stride函数 数组分割 分组

swift stride函数 数组分割 分组

作者: 相约星期二GM | 来源:发表于2018-12-29 23:44 被阅读0次

    stride函数,为可变步长类型值的序列

    其中from to,最后一个值将会小(大)于to的值

    for index in stride(from:0, to:3, by:1)  {
        print(index)
    }
    // print 0, 1, 2
    
    for index in stride(from:3, to:0, by:-1) {
        print(index)
    }
    // print 3,2,1
    

    from through,最后一个值将会小(大)于等于through的值

    for index in stride(from:0, through:3, by:1)  {
        print(index)
    }
    // print 0, 1, 2, 3
    
    for index in stride(from:3, through:0, by:-1)  {
        print(index)
    }
    // print 3,2,1,0
    

    调整by参数(步长)

    for index in stride(from: 0, to: 9, by: 3) {
        print(index)
    }
    // print 0, 3, 6
    
    //  through,包含末尾
    for index in stride(from: 0, through: 9, by: 3) {
      print(index)
    }
    // prints 0, 3, 6, 9
    

    数组分割
    ps:步长与数组元素个数刚好整数倍,否则多出的元素会舍去

    var array = Array(1...10)
    let group1Arr = stride(from: 0, to: 8, by: 4).map {
        print(array[$0...$0+3])
    }
    //[1, 2, 3, 4]
    //[5, 6, 7, 8]
    
    let group2Arr = stride(from: 0, to: 8, by: 4).map {
          Array(array[$0...$0+3])
    }
    print(group2Arr) 
    // [[1, 2, 3, 4], [5, 6, 7, 8]]
    

    let step = 3
    let finalArray = stride(from: 0, to: array.endIndex - (array.endIndex % step), by: step).map {
        Array(array[$0...$0+(step - 1)])
    }
    // step = 2
    // [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
    // step = 3
    // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    

    相关文章

      网友评论

        本文标题:swift stride函数 数组分割 分组

        本文链接:https://www.haomeiwen.com/subject/acsmlqtx.html