Allow using collection accessors on strings (#245)

* allow using collection accessors on strings

* refactored resolving collection accessors

* refactored to fileprivate function

* Update Variable.swift

* Update templates.rst
This commit is contained in:
Ilya Puchka
2018-09-22 16:41:45 +03:00
committed by GitHub
parent df2e193891
commit d238c25eef
4 changed files with 109 additions and 47 deletions

View File

@@ -87,19 +87,9 @@ public struct Variable : Equatable, Resolvable {
current = dictionary[bit]
}
} else if let array = current as? [Any] {
if let index = Int(bit) {
if index >= 0 && index < array.count {
current = array[index]
} else {
current = nil
}
} else if bit == "first" {
current = array.first
} else if bit == "last" {
current = array.last
} else if bit == "count" {
current = array.count
}
current = resolveCollection(array, bit: bit)
} else if let string = current as? String {
current = resolveCollection(string, bit: bit)
} else if let object = current as? NSObject { // NSKeyValueCoding
#if os(Linux)
return nil
@@ -128,6 +118,24 @@ public struct Variable : Equatable, Resolvable {
}
}
private func resolveCollection<T: Collection>(_ collection: T, bit: String) -> Any? {
if let index = Int(bit) {
if index >= 0 && index < collection.count {
return collection[collection.index(collection.startIndex, offsetBy: index)]
} else {
return nil
}
} else if bit == "first" {
return collection.first
} else if bit == "last" {
return collection[collection.index(collection.endIndex, offsetBy: -1)]
} else if bit == "count" {
return collection.count
} else {
return nil
}
}
/// A structure used to represet range of two integer values expressed as `from...to`.
/// Values should be numbers (they will be converted to integers).
/// Rendering this variable produces array from range `from...to`.