Skip to content

Instantly share code, notes, and snippets.

@usagimaru
Last active March 1, 2024 04:58
Show Gist options
  • Save usagimaru/02bf4626cbadf19a2ac38a5cd2cc0434 to your computer and use it in GitHub Desktop.
Save usagimaru/02bf4626cbadf19a2ac38a5cd2cc0434 to your computer and use it in GitHub Desktop.
Initialize IndexPath with description in Swift
import Foundation
extension IndexPath {
enum IndexPathFromStringError: Error {
case couldNotInitialize(String)
}
/// Initialize with description. e.g. "[2, 3, 12, 0, 4]"
init(from description: String) throws {
let regex = /\[((\d+)(, \d+)*)\]/
if let match = description.firstMatch(of: regex)?.1 {
let elements = match.split(separator: ", ").map { Int($0) ?? 0 }
self.init(indexes: elements)
}
else {
throw IndexPathFromStringError.couldNotInitialize(description)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment