简体   繁体   中英

What is the correct syntax for creating an Object Array in Swift?

I created two separate files [ Page.swift and PageTableViewController.swift ]

In Page.swift :

    class Page {

        // MARK: Properties
        var chapter: Int
        var verse: Int
        var sanskrit: String?

        // MARK: Initialization
        init?(chapter: Int, verse: Int, sanskrit: String?)    {
            // Initialize stored properties.
            self.chapter      = chapter
            self.verse        = verse
            self.sanskrit     = sanskrit
        }


    }

And in my PageTableViewController.swift :

import UIKit

class PageTableViewController: UITableViewController {

    // MARK: Properties
    var pages = [Page]()


    override func viewDidLoad() {
        super.viewDidLoad()
        createPages()
    }

    func createPages() {

        let page1 = Page(chapter: 1, verse: 1, sanskrit: "अथ योगानुशासनम्")
        let page2 = Page(chapter: 1, verse: 2, sanskrit: "योगश्चित्तवृत्तिनिरोधः")

        pages += [page1, page2] // ERROR appears here as noted below..


    }

}

But where the error appears, I get :

Binary operator '+=' cannot be applied to operands of type '[Page]' and '[Page?]'

Why would that be?

The answer stares you right in the eye:

Binary operator '+=' cannot be applied to operands of type '[Page]' and '[Page?]'

[page1, page2] is an array of optional Page. You can't add an array of optional Page to an array of Page.

Why is [page1, page2] an array of optional Page? Because page1 and page2 are optional Page.

Why is page1 an optional Page? Because your init method returns an optional Page. It's called init? and not init.

Why is your init method returning an optional Page? Because that's what your code says. I can't see a reason why you did that, but that's what you did.

(Now there might be other reasons why it fails after you fix your init method to return a non-optional page).

In Swift there is no += operand for interacting with array values (for adding to an existent array you would use append). I loaded your code into a Playground and found by replacing the += with just an = sign the array functioned. However, because your init for pages is optional I had to unwrap page 1 and page 2:

if let page1 = page1,
  page2 = page2 {
    pages = [page1, page2] //Unwrapped values added to array, fixes error
}

Another possible solution so you don't need to always unwrap these values or use exclamation points to force unwrap them is to simply remove the ? from the init for Page objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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