Library reference

Remove spaces at both ends

Remove the spaces before and after a name. A space between two words stays in place. These examples use ordinary spaces.

String.trimmingCharacters

Simple example

Trim the single letter.

Start' a '
Resulta
main.swift
import Foundation

print(" a ".trimmingCharacters(in: .whitespaces))
Output
a
Advertisements

Everyday examples

Remove the extra spaces copied around a ticket number.

Start' B12 '
ResultB12
main.swift
import Foundation

print("  B12 ".trimmingCharacters(in: .whitespaces))
Output
B12

Clean up the outside spaces on a shelf label.

Start' Red Apples '
ResultRed Apples
main.swift
import Foundation

print(" Red Apples  ".trimmingCharacters(in: .whitespaces))
Output
Red Apples

Clean up a name copied from a signup sheet.

Start' Ana '
ResultAna
main.swift
import Foundation

print("  Ana ".trimmingCharacters(in: .whitespaces))
Output
Ana
Run the example
Terminal
swift main.swift
Official documentation