简体   繁体   中英

Mapping an array of classes to remove whitespace from values swift

I have a struct and an array of my structs as follows

struct Products{
    var ProductType: String
    var ProductName: String
    var ProductLink: String
}

var CleaningProductsArray = [Products]()

When I write to my array of structs the ProductName Variable inside it sometimes can be written by the user with trailing whitespaces. I would like to return a version of the CleaningProductsArray but with all instances of ProductName having any trailing whitespaces removed. I have been trying to achieve with map as below but does not return what I would like it to. What is the most efficient way to do this?

let trimmed = CleaningProductsArray.map{ $0.ProductName.trimmingCharacters(in: .whitespaces) }

Quick answer is:

let trimmed: [Products] = CleaningProductsArray.map { product in
    var adjusted = product
    adjusted.ProductName = product.ProductName.trimmingCharacters(in: .whitespaces)
    return adjusted
}

As it was correctly mentioned in the comments, there are things you can improve in your overall code design.

You could start with converting your model to meet Swift naming standards, which means not using plural for Products since the objects of this type describe a single product, and removing the product prefix from properties since its obvious from the context that they describe a "Product". Ideally you would also make the properties immutable, to make passing them around safer (google "Benefits of immutability"). You should create some other object responsible for collecting all the data for your product objects.

struct Product {
    let type: String
    let name: String
    let link: String
}

Also, you should never use uppercased names for your variables/constants/properties/functions in Swift, so it's best to replace the CleaningProductsArray with cleaningProductsArray for the sake of readability. Uppercased names are reserved for types. Also you might want to drop the Array suffix since it's obvious from the type that it is an array

var cleaningProducts = [Product]()
let trimmed: [Product] = cleaningProducts.map {
    Product(
        type: $0.type,
        name: $0.name.trimmingCharacters(in: .whitespaces),
        link: $0.link
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM