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
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer.
Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.
In Swift, all structs come with a default initializer. This is called the memberwise initializer. A memberwise initializer assigns each property in the structure to self. This means you do not need to write an implementation for an initializer in your structure.
Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer's parameters set to default values.
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() { }
}
Providing all members with a default value, in this case
var name: String? = nil
fixes the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With