You can use regular expressions:
let string = "813 - Crying Flute.mp3"
let regex = try! NSRegularExpression(pattern: "^(.*) - (.*)\\.(.*)$")
if let match = regex.firstMatch(in: string, range: string.nsRange) {
let title = string[match.range(at: 1)]
let name = string[match.range(at: 2)]
let format = string[match.range(at: 3)]
}
Where, in Swift 4:
extension String {
/// An `NSRange` that represents the full range of the string.
var nsRange: NSRange {
return NSRange(startIndex ..< endIndex, in: self)
}
/// Substring from `NSRange`
///
/// - Parameter nsRange: `NSRange` within the string.
/// - Returns: `Substring` with the given `NSRange`, or `nil` if the range can't be converted.
subscript(nsRange: NSRange) -> Substring? {
return Range(nsRange, in: self)
.flatMap { self[$0] }
}
}
The regular expression's ( and ) are "capturing parentheses" to identify the substrings, that can be identified by range(at:).