如何根据用户选择组合数组?

时间:2016-12-19 10:00:47

标签: ios arrays swift xcode

我希望看到用户选择的内容,如书名及其相关章节

我做了这个

struct bookChpt {
    var book:[String] = []
    var chapter:[[Int]] = []
}

let chptSelected = [bookChpt(book:bookArr,chapter:chptArr)]

var bookArr:[String] = []
var chptArr:[[Int]] = []

我在viewDidLoad()

中有这个
if let bTitle = result.value(forKey: "bookTitle") as? String
{
    bookArr.append(bTitle)

}
if let cNo = result.value(forKey: "chpNo") as? [Int]
{
    chptArr.append(cNO)
}
print(chptSelected)

我收到了这个

  

bookChpt(书:[“霍比特人”,“LOTR”],章节:[[3,5],4])

但我喜欢看到这个

  

[“Hobbit”,3,5],[“LOTR”,4]

3 个答案:

答案 0 :(得分:3)

有几种可能性。您可以向结构添加一个函数,以您希望的方式显示其内容:

struct BookChapter {
    var book:[String] = []
    var chapter:[[Int]] = []

    func display() -> [[Any]] {
        var output = [[Any]]()
        for i in 0..<book.count {
            output.append([book[i], chapter[i]])
        }
        return output
    }
}

或者您可以修改结构的结构以包含本书和章节作为元组:

struct BookChapter {
    var book:[(String, [Int])]
}

进一步,在你看到循环的任何地方 - 比如上面的显示功能 - 你也可以考虑使用map来实现同样的目的:

func display() -> Any {
    return book.enumerated().map { $0.element + " " + chapter[$0.offset].description }
}

答案 1 :(得分:1)

如果你使用这样的词典,你可以按照你想要的方式打印键和值。

var bookChapters = [String: [Int]]()

bookChapters["Hobbit"] = [1,2,3]
bookChapters["Hobbit"]?.append(contentsOf: [4])


for (book, chapter) in bookChapters {
    print("\(book): \(chapter)")
}

答案 2 :(得分:0)

struct更改为

struct BookChapt {
    var book: String = ""
    var chapter: [Int] = []
}

并在viewDidLoad()

var bookName = ""
var chapters:[Int] = []
if let bTitle = result.value(forKey: "bookTitle") as? String
{
    bookName = bTitle
}
if let cNo = result.value(forKey: "chpNo") as? [Int]
{
    chapters = cNo
}
let chptSelected = BookChapt(book: bookName, chapter: chapters)
print(chptSelected)