在Swift中,我可以编写通用函数来调整数组大小吗?

Rol*_*ien 2 swift

我有这个功能:

func sizeArray(inout array:Array<String>, size:Int) {

    while (array.count < size) {
        array.append("")
    }

    while (array.count > size) {
        array.removeLast()
    }
}
Run Code Online (Sandbox Code Playgroud)

它可以工作,但仅适用于字符串数组,我可以使其与任何类型通用吗?

ken*_*ytm 6

最通用的方法...

  1. Array调整RangeReplaceableCollection协议,其中包括可以帮助调整大小的方法。(无需使用循环)

  2. 增长数组时,您需要构造该元素的新实例。因此,您可以提供一个默认值...

extension RangeReplaceableCollection {
    public mutating func resize(_ size: IndexDistance, fillWith value: Iterator.Element) {
        let c = count
        if c < size {
            append(contentsOf: repeatElement(value, count: c.distance(to: size)))
        } else if c > size {
            let newEnd = index(startIndex, offsetBy: size)
            removeSubrange(newEnd ..< endIndex)
        }
    }
}

var f = ["a", "b"]
f.resize(5, fillWith: "")    // ["a", "b", "", "", ""]
f.resize(1, fillWith: "")    // ["a"]
Run Code Online (Sandbox Code Playgroud)
  1. 或者您创建提供默认值的协议init()。请注意,您需要手动调整协议以适应您关心的每种类型。
public protocol DefaultConstructible {
    init()
}

extension String: DefaultConstructible {}
extension Int: DefaultConstructible {}
// and so on...

extension RangeReplaceableCollection where Iterator.Element: DefaultConstructible {
    public mutating func resize(_ size: IndexDistance) {
        resize(size, fillWith: Iterator.Element())
    }
}

var g = ["a", "b"]
g.resize(5)
g.resize(1)
Run Code Online (Sandbox Code Playgroud)