Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
60 views
in Technique[技术] by (71.8m points)

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) }
question from:https://stackoverflow.com/questions/65865715/mapping-an-array-of-classes-to-remove-whitespace-from-values-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...