Last active
March 1, 2024 04:58
-
-
Save usagimaru/02bf4626cbadf19a2ac38a5cd2cc0434 to your computer and use it in GitHub Desktop.
Initialize IndexPath with description in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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