What is the syntax for multidimensional array in Swift?

后端 未结 2 1980
慢半拍i
慢半拍i 2021-01-26 13:42

CO fans: before you jump into conclusion it is a duplicate, there are 2 distinct flavours of arrays, and it seems I am asking about less popular one.

So far, I

2条回答
  •  清歌不尽
    2021-01-26 14:20

    An example implementation supporting arbitrary number of dimensions:

    struct ArrayMultiDimension {
        private var _base:[T]
        let _dimensions: [Int]
    
        init(initialValue: T, dimensions:Int...) {
            _base = Array(count: reduce(dimensions, 1, *), repeatedValue: initialValue)
            _dimensions =  dimensions
        }
        private func _position2idx(position:[Int]) -> Int {
            assert(position.count == _dimensions.count)
            return reduce(Zip2(_dimensions, position), 0) {
                assert($1.0 > $1.1)
                return $0 * $1.0 + $1.1
            }
        }
        subscript(position:Int...) -> T {
            get { return _base[_position2idx(position)] }
            set { _base[_position2idx(position)] = newValue }
        }
    }
    
    // Usage:
    
    var array3d = ArrayMultiDimension(initialValue: "", dimensions: 4,3,2)
    
    for x in 0 ..< 4 {
        for y in 0 ..< 3 {
            for z in 0 ..< 2 {
                array3d[x,y,z] = "\(x)-\(y)-\(z)"
            }
        }
    }
    
    array3d[1,2,0] = "foo"
    

    But, this could be very slow...

提交回复
热议问题