tegi
2/11/2018 - 9:15 AM

Substring before a separator in Swift (Useful for enums with associated types)

Substring before a separator in Swift (Useful for enums with associated types)

func testSubstringBeforeSeparator() {
    let strings = [
        "abc(xyz)" : "abc",
        "abc" : "abc",
        "abc(xyz(123))" : "abc",
        "abc[xyz]" : "abc[xyz]"
    ]
    let separator = "("
    
    strings.forEach { (input, expected) in
        let output = StringUtil.substring(input, beforeSeparator: separator)
        debugPrint("\(expected) : \(output)")
        XCTAssertEqual(expected, output)
    }
}
/// Substring before a separator.
///
/// "abc(xyz)" with "(" as the separator becomes "abc"
///
/// - Parameters:
///   - value: value
///   - separator: separator
/// - Returns: stripped result
public static func substring(_ value: String, beforeSeparator separator: String) -> String {
    guard let range = value.range(of: separator) else {
        return value
    }
    return value.substring(to: range.lowerBound)
}