PathTemplate 的 Swift 实现,用于处理模板化的路径。灵感来源于 path-to-regexp 和 URITemplate.swift。
将以下内容添加到您的 Package.swift
文件的 dependencies: []
中
.package(url: "https://github.com/gjeck/PathTemplate.swift.git")
将以下内容添加到您的 Podfile
文件中
pod 'PathTemplate'
PathTemplate
对于处理结构化的 String
数据(例如 URL)非常有用。
let template: PathTemplate = "/user/:id"
template.expand(["id": 123])
=> "/user/123"
let template: PathTemplate = "https://api.github.com/repos/:owner/:repo/"
template.parameterNames
=> ["owner", "repo"]
let template: PathTemplate = "/artist/:artistId/album/:albumId"
template.extract("/artist/123/album/456")
=> ["artistId": "123", "albumId": "456"]
命名参数通过在单词字符 [A-Za-z0-9_]
的段前加上冒号来定义,例如 :user
。可以添加额外的修饰符以表示不同的含义
?
参数是可选的*
零个或多个段+
一个或多个段let template: PathTemplate = "https://:hostname/:path?"
template.expand(["hostname": "github.com"])
=> "https://github.com"
template.expand(["hostname": "github.com", "path": "user"])
=> "https://github.com/user"
let template: PathTemplate = "https://:hostname/:path*"
template.expand(["hostname": "github.com", "path": ["user", "gjeck"]])
=> "https://github.com/user/gjeck"
template.expand(["hostname": "github.com"])
=> "https://github.com"
let template: PathTemplate = "https://:hostname/:path+"
template.expand(["hostname": "github.com", "path": ["user", "gjeck"]])
=> "https://github.com/user/gjeck"
template.expand(["hostname": "github.com"])
=> nil
可以为参数提供自定义正则表达式,以覆盖默认匹配。例如,您可以强制匹配路径中的数字。
let template: PathTemplate = "/image-:imageId(\\d+).png"
template.expand(["imageId": 123])
=> "/image-123.png"
template.expand(["imageId": "abc"])
=> nil
可以编写一个仅包含匹配组的未命名参数。它的工作方式与命名参数相同,只不过它将被数字索引。
let template: PathTemplate = "/cool/(\\d+)/(.*)"
template.parameterNames
=> ["0", "1"]
template.expand(["0": 123, "1": "wow"])
=> "/cool/123/wow"
let template = PathTemplate("/User/:id", options: .init(isCaseSensitive: true))
template.extract("/user/123") // Note that "user" has a lowercase "u"
=> []
let template: PathTemplate = "/user/:id"
template.regex
=> <NSRegularExpression: 0x102745860> ^\/user\/([^\/]+?)(?:\/)?$