From 1e3afc0dd548d2ba4a145329d6b6fb6534df44e7 Mon Sep 17 00:00:00 2001 From: Kyle Fuller Date: Thu, 13 Oct 2016 13:11:02 +0100 Subject: [PATCH] fix(variable): Prevent crash on unknown index in array --- CHANGELOG.md | 10 ++++++++++ Sources/Variable.swift | 6 +++++- Tests/StencilTests/VariableSpec.swift | 14 ++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 186afc1b..a2230d4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,14 @@ # Stencil Changelog + +## Master + +### Bug Fixes + +- Variables (`{{ variable.5 }}`) that reference an array index at an unknown + index will now resolve to `nil` instead of causing a crash. + [#72](https://github.com/kylef/Stencil/issues/72) + + ## 0.6.0 ### Enhancements diff --git a/Sources/Variable.swift b/Sources/Variable.swift index 1a4070bf..8a523d70 100644 --- a/Sources/Variable.swift +++ b/Sources/Variable.swift @@ -64,7 +64,11 @@ public struct Variable : Equatable, Resolvable { current = dictionary[bit] } else if let array = current as? [Any] { if let index = Int(bit) { - current = array[index] + if index >= 0 && index < array.count { + current = array[index] + } else { + current = nil + } } else if bit == "first" { current = array.first } else if bit == "last" { diff --git a/Tests/StencilTests/VariableSpec.swift b/Tests/StencilTests/VariableSpec.swift index a42f9107..27136269 100644 --- a/Tests/StencilTests/VariableSpec.swift +++ b/Tests/StencilTests/VariableSpec.swift @@ -52,6 +52,20 @@ func testVariable() { let variable = Variable("contacts.0") let result = try variable.resolve(context) as? String try expect(result) == "Katie" + + let variable1 = Variable("contacts.1") + let result1 = try variable1.resolve(context) as? String + try expect(result1) == "Carlton" + } + + $0.it("can resolve an item from an array via unknown index") { + let variable = Variable("contacts.5") + let result = try variable.resolve(context) as? String + try expect(result).to.beNil() + + let variable1 = Variable("contacts.-5") + let result1 = try variable1.resolve(context) as? String + try expect(result1).to.beNil() } $0.it("can resolve the first item from an array") {