0

我正在使用 Swift 5 进行服务器端开发(Kitura),并且由于模板引擎没有办法修剪长文本(想想博客文章的正文),我想知道如何直接在 Swift 中修剪它。其他问题以不同的方式解决它(只是一个不是来自循环的字符串)所以这是我的代码:

router.get("/admin", handler: {
 request , response,next  in

    let documents = try collection.find()
    var pages: [[String: String]] = []

    for d in documents {
        print(d)
        pages.append(["title": d.title, "slug": d.slug, "body": d.body, "date": d.date])


 // I would like to trim the value of d.body

        print(d)
    }
    // check if an error occurred while iterating the cursor
    if let error = documents.error {
        throw error
    }
    try response.render("mongopages.stencil", with: ["Pages": pages])
    response.status(.OK)
})

return router
}()

如何修剪 d.body 的值以将其修剪为前 50 个字符?

4

1 回答 1

3

您可以扩展String为您提供此功能(或提取它)。

extension String {
    func truncate(to limit: Int, ellipsis: Bool = true) -> String {
        if count > limit {
            let truncated = String(prefix(limit)).trimmingCharacters(in: .whitespacesAndNewlines)
            return ellipsis ? truncated + "\u{2026}" : truncated
        } else {
            return self
        }
    }
}

let default = "Coming up with this sentence was the hardest part of this.".truncate(to: 50)
print(default) // Coming up with this sentence was the hardest part…

let modified = "Coming up with this sentence was the hardest part of this.".truncate(to: 50, ellipsis: false)
print(modified) // Coming up with this sentence was the hardest part

在您的用例中:

router.get("/admin", handler: { (request, response, next)  in
    let documents = try collection.find()
    var pages: [[String: String]] = []
    
    for d in documents {
        let truncatedBody = d.body.truncate(to: 50)
        pages.append(["title": d.title, "slug": d.slug, "body": truncatedBody, "date": d.date])
    }
    
    ...
})
于 2020-12-07T20:58:48.843 回答