Skip to content

Instantly share code, notes, and snippets.

@starhoshi
Last active June 29, 2017 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starhoshi/141eb7d7757936052facc03fc9bb1aed to your computer and use it in GitHub Desktop.
Save starhoshi/141eb7d7757936052facc03fc9bb1aed to your computer and use it in GitHub Desktop.
https://google.com/ のような、最後に / だけ付いている場合に / を削除する
public extension URL {
public func removeLastSlash() -> URL {
let separator = "/"
let schemeSeparator = "://"
var paths = path.components(separatedBy: separator)
if let lastPaths = paths.last, lastPaths == "", let host = self.host, let scheme = self.scheme {
paths.removeLast()
let urlString = scheme + schemeSeparator + host + paths.joined(separator: separator)
return URL(string: urlString) ?? self
}
return self
}
}
import Quick
import Nimble
class URLExtensionSpec: QuickSpec {
override func spec() {
let urlWithLastSlash = URL(string: "https://google.com/")!
let urlWithoutLastSlash = URL(string: "https://google.com")!
describe("removeLastSlash()") {
context("URL の末尾に / がある場合") {
it("/ が削除されていること") {
expect(urlWithLastSlash.removeLastSlash().absoluteString).to(equal(urlWithoutLastSlash.absoluteString))
}
}
context("URL の末尾に / がない場合") {
it("URL に変化がないこと") {
expect(urlWithoutLastSlash.removeLastSlash().absoluteString).to(equal(urlWithoutLastSlash.absoluteString))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment