swiftswift5kitura

Trimming a String inside a loop in Swift 5


I am using Swift 5 for a server side development (Kitura) and since the template engine doesn't have a way to trim long text (think the body of a blog post) I was wondering how to trim it in Swift directly. Other questions address it differently (just a string not from a loop) so here is my code:

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

how to trim the value of d.body to trim it to the first 50 characters?


Solution

  • You can extend String to give you this functionality (or extract it).

    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
    

    And in your use case:

    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])
        }
        
        ...
    })