From 7b22f79d7910f8670bb3f24cf23985300884474e Mon Sep 17 00:00:00 2001 From: David Jennes Date: Thu, 1 Jun 2017 00:55:51 +0200 Subject: [PATCH] Modify the removeNewlines code to use the new enum parser --- Sources/Filters+Strings.swift | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/Sources/Filters+Strings.swift b/Sources/Filters+Strings.swift index 2b7d5e5f..3029651e 100644 --- a/Sources/Filters+Strings.swift +++ b/Sources/Filters+Strings.swift @@ -7,6 +7,10 @@ import Foundation import Stencil +enum RemoveNewlinesModes: String { + case all, leading +} + extension Filters { enum Strings { fileprivate static let reservedKeywords = [ @@ -119,23 +123,31 @@ extension Filters { return escapeReservedKeywords(in: string) } + /// Removes newlines and other whitespace from a string. Takes an optional Mode argument: + /// - all (default): remove all newlines and whitespaces + /// - leading: remove newlines and only leading whitespaces + /// + /// - Parameters: + /// - value: the value to be processed + /// - arguments: the arguments to the function; expecting zero or one mode argument + /// - Returns: the trimmed string + /// - Throws: FilterError.invalidInputType if the value parameter isn't a string static func removeNewlines(_ value: Any?, arguments: [Any?]) throws -> Any? { - let mode = arguments.first as? String ?? "all" + guard let string = value as? String else { throw Filters.Error.invalidInputType } + let mode = try Filters.parseEnum(from: arguments, default: RemoveNewlinesModes.all) switch mode { - case "all": + case .all: return string .components(separatedBy: .whitespacesAndNewlines) .joined() - case "leading": + case .leading: return string .components(separatedBy: .newlines) .map { String($0.unicodeScalars.drop(while: { CharacterSet.whitespaces.contains($0) })) } .joined() .trimmingCharacters(in: .whitespaces) - default: - throw Filters.Error.invalidOption(option: mode) } }