Created
February 25, 2021 23:41
-
-
Save codelynx/f4eb013d7a6b34da755ddefb948d27ff to your computer and use it in GitHub Desktop.
string by incremented trailing number good for a suggestion of duplicated file name
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
// String+Z.swift | |
// ZKit | |
// | |
// The MIT License (MIT) | |
// | |
// Copyright (c) 2016 Electricwoods LLC, Kaz Yoshikawa. | |
// | |
// Permission is hereby granted, free of charge, to any person obtaining a copy | |
// of this software and associated documentation files (the "Software"), to deal | |
// in the Software without restriction, including without limitation the rights | |
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
// copies of the Software, and to permit persons to whom the Software is | |
// furnished to do so, subject to the following conditions: | |
// | |
// The above copyright notice and this permission notice shall be included in | |
// all copies or substantial portions of the Software. | |
// | |
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, | |
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | |
// THE SOFTWARE. | |
// | |
// Usage: | |
// "0".incrementingTrailingNumber() // "1" | |
// "1".incrementingTrailingNumber() // "2" | |
// "Untitled".incrementingTrailingNumber() // "Untitled2" | |
// "Untitled1".incrementingTrailingNumber() // "Untitled2" | |
// "Untitled2".incrementingTrailingNumber() // "Untitled3" | |
// "Untitled-3".incrementingTrailingNumber() // "Untitled-4" | |
// "Untitled 3".incrementingTrailingNumber() // "Untitled 4" | |
import Foundation | |
public extension String { | |
func incrementingTrailingNumber() -> String { | |
if let range = self.range(of: "[0-9]+$", options: [.regularExpression]), let number = Int(self[range]) { | |
return self.replacingCharacters(in: range, with: String(number + 1)) | |
} | |
return self + "2" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment