From 14bac03990683b830014816ff33a199624d545f2 Mon Sep 17 00:00:00 2001 From: Yonas Kolb Date: Tue, 2 May 2017 14:52:55 +0800 Subject: [PATCH] feat(variable): Allow accessing dictionary count --- CHANGELOG.md | 2 ++ Sources/Variable.swift | 6 +++++- Tests/StencilTests/VariableSpec.swift | 9 +++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2494ee2..2bd4458 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,8 @@ - Introduces a new `DictionaryLoader` for loading templates from a Swift Dictionary. - Added `in` expression in if tag for strings and arrays of hashable types +- You can now access the amount of items in a dictionary using the `count` + property. ### Bug Fixes diff --git a/Sources/Variable.swift b/Sources/Variable.swift index ea0353a..c330d64 100644 --- a/Sources/Variable.swift +++ b/Sources/Variable.swift @@ -74,7 +74,11 @@ public struct Variable : Equatable, Resolvable { if let context = current as? Context { current = context[bit] } else if let dictionary = current as? [String: Any] { - current = dictionary[bit] + if bit == "count" { + current = dictionary.count + } else { + current = dictionary[bit] + } } else if let array = current as? [Any] { if let index = Int(bit) { if index >= 0 && index < array.count { diff --git a/Tests/StencilTests/VariableSpec.swift b/Tests/StencilTests/VariableSpec.swift index d66dc1a..ac532a3 100644 --- a/Tests/StencilTests/VariableSpec.swift +++ b/Tests/StencilTests/VariableSpec.swift @@ -26,6 +26,9 @@ func testVariable() { "profiles": [ "github": "kylef", ], + "counter": [ + "count": "kylef", + ], "article": Article(author: Person(name: "Kyle")) ]) @@ -107,6 +110,12 @@ func testVariable() { try expect(result) == "Kyle" } + $0.it("can get the count of a dictionary") { + let variable = Variable("profiles.count") + let result = try variable.resolve(context) as? Int + try expect(result) == 1 + } + #if os(OSX) $0.it("can resolve a value via KVO") { let variable = Variable("object.title")