algo/swift/05_array/MyArray.swift
2018-10-11 19:09:50 +08:00

78 lines
2.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// Created by Jiandan on 2018/10/10.
// Copyright (c) 2018 Jiandan. All rights reserved.
//
import Foundation
// <Element> Swift
public struct MyArray<Element> {
private var data: [Element]
private var capacity = 0 //
private var count = 0 //
///
/// - parameter defaultElement:
/// - parameter capacity:
init(defaultElement: Element, capacity: Int) {
data = [Element](repeating: defaultElement, count: capacity)
self.capacity = capacity
}
// index
func find(at index: Int) -> Element? {
// index [0, count)
guard index >= 0, index < count else {
return nil
}
return data[index]
}
// index
mutating func delete(at index: Int) -> Bool {
// index [0, count)
guard index >= 0, index < count else {
return false
}
// [index, count - 1) index
for i in index ..< count - 1 {
data[i] = data[i+1]
}
count -= 1
return true
}
// index
mutating func insert(value: Element, at index: Int) -> Bool {
// index [0, count)
guard index >= 0, index < count, count < capacity else {
return false
}
// count - 1 ~ index
for i in (index ... count - 1).reversed() {
data[i + 1] = data[i]
}
data[index] = value
count += 1
return true
}
//
mutating func add(value: Element) -> Bool {
guard count < capacity else {
return false
}
data[count] = value
count += 1
return true
}
func printAll() {
print("\(data)")
}
}