如何构建一对多对多对多数据结构Swift

时间:2015-05-31 23:45:20

标签: ios swift class

我很难弄清楚如何最好地规划出一个吸引用户的数据结构,添加与该用户相关的品牌,然后添加服装项目和用户的大小(为此品牌的关闭项目,对于该用户而言)。

class User {

     var name: String

     class Brands : User {

          var brandName: [String]

          class ItemAndSize : Brands {
               var itemAndSize: [String: Int]
          }

     }

}

有没有更好的方法在Swift中构建它?我希望能够存储并调用user.brandName.itemAndSize。

1 个答案:

答案 0 :(得分:2)

最好的可能不是使用继承来创建关系。人,物体和规格之间的关系可以通过在表格中映射来解决。在下面的示例中,我将'item'与'sizing'分开,因为除非您通过连接主键来组成密钥,否则字典将不会将用户映射到品牌和item / sizing:

struct User {
    var id: Int
    var description: String
}

struct Brand {
    var id: Int
    var description: String
}

enum Sizing {
    case S, M, L, XL

    var description : String {
        switch self {
            case .S: return "S";
            case .M: return "M";
            case .L: return "L";
            case .XL: return "XL";
        }
    }
}

enum Clothing {
    case Pants, Shorts, Shirt, Jacket

    var description : String {
        switch self {
        case .Pants: return "Pants";
        case .Shorts: return "Shorts";
        case .Shirt: return "Shirt";
        case .Jacket: return "Jacket";
        }
    }
}

struct Mapping {
    var user: User
    var brand: Brand
    var item: Clothing
    var size: Sizing
}

let users = [User(id: 1, description: "Pierre"), User(id: 2, description: "Paul"), User(id: 3, description: "Jacques")]
let brands = [Brand(id: 1, description: "D&G"), Brand(id: 2, description: "Gucci"), Brand(id: 3, description: "Prada")]

let mappings = [Mapping(user: users[0], brand: brands[1], item: .Pants, size: .XL),
    Mapping(user: users[1], brand: brands[0], item: .Jacket, size: .S)]


for m in mappings {
    var s = ",".join([m.user.description, m.brand.description, m.item.description, m.size.description])
    println(s)
}