如何改变数组

时间:2017-06-12 17:40:06

标签: arrays swift dictionary struct mutation

我需要改变以下数组:

struct Person {
    var name: String
    var age = 0
    }

func showPersonArray() -> [Person] {

    var dataArray = [Person]()

    dataArray.append(Person(name: "Sarah_Yayvo", age: 29))
    dataArray.append(Person(name: "Shanda_Lear", age: 45))
    dataArray.append(Person(name: "Heidi_Clare", age: 45))

    return dataArray
}

我怎么能将“name”-key分成两个键:“givenName”和“familyName”。 一些好人之前给了我这个代码:

let arraySeparated1 = dataArray.map { $0.substring(to: $0.range(of: "_")!.lowerBound) }
let arraySeparated2 = dataArray.map { $0.substring(from: $0.range(of: "_")!.upperBound) }

是否有可能在结构内部进行突变? showPersonArray()函数仅用于演示和测试。 也许有一种方法可以使用目标结构,如下所示:

struct Persontarget {
    var familyname: String
    var givenName: String
    var age = 0
}

struct Person: Array -> [Persontarget]  {
    var name: String
    var age = 0

    // Here the split/mutating code

    return [PersonWithTwoNames]
}

或者使用String扩展名。可能我的问题听起来很新鲜,但我正在尝试一整天...... 谢谢大家!

3 个答案:

答案 0 :(得分:1)

我会在新的Person类型上写一个初始值设定项,它从旧的人类型(我称之为LegacyPerson)初始化它:

import Foundation

struct LegacyPerson {
    let name: String
    let age: Int
}

func getPersonArray() -> [LegacyPerson] {
    return [
        LegacyPerson(name: "Sarah_Yayvo", age: 29),
        LegacyPerson(name: "Shanda_Lear", age: 45),
        LegacyPerson(name: "Heidi_Clare", age: 45)
    ]
}

struct Person {
    let familyName: String
    let givenName: String
    let age: Int
}

extension Person {
    init(fromLegacyPerson person: LegacyPerson) {
        let index = person.name.range(of: "_")!
        self.init(
            familyName: person.name.substring(from: index.upperBound),
            givenName: person.name.substring(to: index.lowerBound),
            age: person.age
        )
    }
}

let people: [Person] = getPersonArray().map(Person.init)

people.forEach{ print($0) }

答案 1 :(得分:0)

为Person类创建一个返回所需内容的方法或计算机变量。

func firstName() -> String {
    return self.substring(to: $0.range(of: "_")!.lowerBound)
}

你不应该强迫施放

答案 2 :(得分:0)

借助扩展名

中定义的计算属性
struct Person {
    let name: String
    let age: Int
}

let person = Person(name: "Maria_Terezia", age: 300)

extension Person {
    var names:[String] {
        get {
            return name.characters.split(separator: "_").map(String.init)
        }
    }
}

for name in person.names {
    print(name)
}

打印

Maria
Terezia