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?
You can extend
String
to give you this functionality (or extract it).And in your use case: