runios
runios

Reputation: 394

Default Initializer in swift

I created a swift class with string optionals (String?) and instantiated the class in a different swift file and got a compile error. When I instantiate the class within the same file, there is no error. Is there something wrong I am doing? I double checked the behaviour and this behaviour is consistent even with the class definition given in the swift documentation:

class ShoppingListItem {
    var name: String?
    var quantity = 1
    var purchased = false
}
var item = ShoppingListItem()

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/in/jEUH0.l

If the var item = ShoppingListItem() is done in the appDelegate.swift, from the function application:didFinishLaunchingWithOptions we get the error:

<class> cannot be initialised because it has no accessible initializers

OTOH, if we keep the instantiation as soon as the class declaration ends, there is no problem.

Edit: This issue is not a showstopper, the current default initialiser behaviour seems inconsistent or I need to understand it better

Upvotes: 21

Views: 21666

Answers (2)

zrslv
zrslv

Reputation: 1846

Providing all members with a default value, in this case

var name: String? = nil

fixes the error.

Upvotes: 17

HighFlyingFantasy
HighFlyingFantasy

Reputation: 3789

Chances are it's an issue with the Swift compiler and access control (not pointing fingers, just trying to troubleshoot). Add an explicit initializer to the class and see if that works:

class ShoppingListItem {
    var name: String?
    var quantity = 1
    var purchased = false

    init() { }
}

If that doesn't work, then set the class to public, along with the initializer

    public class ShoppingListItem {
        var name: String?
        var quantity = 1
        var purchased = false

        public init() { }
    }

Upvotes: 32

Related Questions