Array+Extension.swift 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //
  2. // ArrayExtension.swift
  3. // CryptoSwift
  4. //
  5. // Created by Marcin Krzyzanowski on 10/08/14.
  6. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
  7. //
  8. extension Array {
  9. init(reserveCapacity: Int) {
  10. self = Array<Element>()
  11. self.reserveCapacity(reserveCapacity)
  12. }
  13. }
  14. extension Array {
  15. /** split in chunks with given chunk size */
  16. func chunks(size chunksize: Int) -> Array<Array<Element>> {
  17. var words = Array<Array<Element>>()
  18. words.reserveCapacity(self.count / chunksize)
  19. for idx in stride(from: chunksize, through: self.count, by: chunksize) {
  20. words.append(Array(self[idx - chunksize ..< idx])) // slow for large table
  21. }
  22. let remainder = self.suffix(self.count % chunksize)
  23. if !remainder.isEmpty {
  24. words.append(Array(remainder))
  25. }
  26. return words
  27. }
  28. }
  29. extension Array where Element: Integer, Element.IntegerLiteralType == UInt8 {
  30. public init(hex: String) {
  31. self.init()
  32. do{
  33. try hex.streamHexBytes { (byte) in
  34. self.append(byte as! Element)
  35. }
  36. } catch _{
  37. self.removeAll()
  38. }
  39. }
  40. }