在 Swift 5 中的循环内修剪字符串

Trimming a String inside a loop in Swift 5

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

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
}()

如何trim将d.body的值trim设为前50个字符?

您可以扩展 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])
    }
    
    ...
})