简体   繁体   English

映射类数组以从值 swift 中删除空格

[英]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.当我写入我的结构数组时,其中的 ProductName 变量有时可以由用户编写,并带有尾随空格。 I would like to return a version of the CleaningProductsArray but with all instances of ProductName having any trailing whitespaces removed.我想返回 CleaningProductsArray 的版本,但 ProductName 的所有实例都删除了任何尾随空格。 I have been trying to achieve with map as below but does not return what I would like it to.我一直在尝试使用 map 实现如下但没有返回我想要的。 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".您可以从转换 model 以符合 Swift 命名标准开始,这意味着不要对Products使用复数,因为这种类型的对象描述单个产品,并从属性中删除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.您应该创建一些其他 object 负责收集您的产品对象的所有数据。

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.此外,您不应该在 Swift 中为您的变量/常量/属性/函数使用大写名称,因此为了便于阅读,最好将CleaningProductsArray替换为cleaningProductsArray 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此外,您可能想要删除Array后缀,因为从类型中可以明显看出它是一个数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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