Apple Swift: Initialize a class in another class - ios

I have some trouble to init() a class in another class.
I've been looking if I can find a solution in here but I wasn't able to.
If I write super.init() there comes another error because the function isn't existing.
I don't know where I have to initialize it.
I'd prefer to init the Address class in the open init from the Contact class but if I do so I can't access the Address class.
I think that it isn't a big mistake but I'm not able to find it.
open class Contact: Identifiable {
public var id: Int64?
var FirstName: String
var Name: String
var Phone: String
var Mail: String
var Birth: String
var News: Bool
open class Adress: Contact {
var Street: String
var Number: String
var PostalCode: String
var City: String
var Country: String // Error:'super.init' isn't called on all paths before returning from initializer
//If I add the Super.Init() there is an error because Super.Init() isn't existing and I don't know where to create it.
init(Street: String, Number: String, PostalCode: String, City: String, Country: String) {
self.Street=Street
self.Number=Number
self.PostalCode=PostalCode
self.City=City
self.Country=Country
}
}
public init(id: Int64, Firstname: String, Name: String, Phone: String, Mail: String, Birth: String, News: Bool) {
self.id = id
self.FirstName = Name
self.Name = Name
self.Phone = Phone
self.Mail = Mail
self.Birth = Birth
self.News = false
}
}

Technically you could do it this way:
class Contact: Identifiable {
public var id: Int64
var name: String
class Address: Contact {
var street: String
init(street: String, contact: Contact) {
self.street = street
super.init(id: contact.id, name: contact.name)
}
}
public init(id: Int64, name: String) {
self.id = id
self.name = name
}
}
let contact = Contact(id: 1, name: "name")
let address = Contact.Address(street: "street", contact: contact)
But maybe you want to model it in a way that a Contact has an Address:
class Contact: Identifiable {
public var id: Int64
var name: String
var address: Address
public init(id: Int64, name: String, address: Address) {
self.id = id
self.name = name
self.address = address
}
}
class Address: Identifiable {
var id: Int64
var street: String
public init(id: Int64, street: String) {
self.id = id
self.street = street
}
}
let address = Address(id: 1, street: "street")
let contact = Contact(id: 2, name: "name", address: address)

Related

Primary key in realm database

I create a default realm file to use it during first launching app as replacement (I want to have a file with initial data). I start with creating default realm file from csv files. The problem is that I am not sure if my structure is correct. When I import data from csv (in Realm Browser) and try to import next data for next class, I get this error
I have main class called Exercises
class Exercises: Object {
#Persisted var id: Int = 0
#Persisted var name: String = ""
#Persisted var category: Category?
#Persisted var equipment: Equipment?
#Persisted var instruction: String
#Persisted var muscle: List<Muscle>
#Persisted var gif: String?
#Persisted var image: String?
convenience init(id: Int, name: String, category: Category?, equipment: Equipment?, instruction: String, muscle: [Muscle], gif: String?, image: String?) {
self.init()
self.id = id
self.name = name
self.category = category
self.equipment = equipment
self.instruction = instruction
self.muscle.append(objectsIn: muscle)
self.gif = gif
self.image = image
}
}
and other classes for separate things
class Equipment: Object {
#Persisted(primaryKey: true) var equipmentID = 0
#Persisted var equipment: String = ""
convenience init(equipment: String) {
self.init()
self.equipment = equipment
}
}
class Category: Object {
#Persisted(primaryKey: true) var categoryID = 0
#Persisted var category: String = ""
convenience init(category: String) {
self.init()
self.category = category
}
}
class Muscle: Object {
#Persisted(primaryKey: true) var muscleID = 0
#Persisted var muscle: String = ""
convenience init(muscle: String) {
self.init()
self.muscle = muscle
}
}
Finally I want to receive structure like below. I wonder if it is correct way? Maybe better option is just set text in fields instead of reference to class (after all realm is non-relational)?

Return from initializer without initializing all stored properties?

I am using separate class to save objects in the class. But it shows an error: "Return from initializer without initializing all stored properties". Please help me to resolve this.
class FetchedExpectedVisitors
{
var id: Int
var name: String
var email: String
var phone: String
var department_id: Int
var employee_id: Int
var location_id: Int
var image: String
var verification_code: String
var qr_code: String
var isVisited: Int
var company_id: Int
var purpose: String
var meeting_date: String
var meeting_time: String
var duration: String
var created_at: String
var updated_at: String
init(id: Int, name: String, email: String, phone: String, department_id: Int, employee_id: Int, location_id: Int, image: String, verification_code: String, qr_code: String, isVisited: Int, company_id: Int, purpose: String, meeting_date: String, meeting_time: String, duration: String, created_at: String, updated_at: String) {
self.id = id
self.name = name
self.email = email
self.phone = phone
self.department_id = department_id
self.location_id = location_id
self.image = image
self.verification_code = verification_code
self.qr_code = qr_code
self.isVisited = isVisited
self.company_id = company_id
self.purpose = purpose
self.meeting_date = meeting_date
self.meeting_time = meeting_time
self.duration = duration
self.created_at = created_at
self.updated_at = updated_at
}
}
Add self.employee_id = employee_id inside init().

Return from initializer without initializing all stored properties swift ios

I am initializing the variables for SQLite database in the WidgetData class but there is an error I have got right now,
Return from initializer without initializing all stored properties
but previously it was running successfully.
I have followed this but even I have added them empty value still getting the error, help to resolve this.
Here is what I have done so far:
import Foundation
class WidgetData {
var id: Int64?
var name: String
var entered : String
var address: String
var formid : Int64?
var formname : String
var formdescription : String
var formcategory : String
init(id: Int64) {
self.id = id
name = ""
entered = ""
address = ""
}
init(formid: Int64) {
self.formid = formid
formname = ""
formdescription = ""
formcategory = ""
}
init(id: Int64, name: String, entered: String, address: String) {
self.id = id
self.name = name
self.entered = entered
self.address = address
}
init(formid: Int64, formname : String, formdescription : String, formcategory : String) {
self.formid = formid
self.formname = formname
self.formdescription = formdescription
self.formcategory = formcategory
}
}
The problem is that the following properties:
var name: String
var entered : String
var address: String
var formname : String
var formdescription : String
var formcategory : String
are not optional, so they must be initialized:
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.
Hence you could assign them a default value, so your code might be:
import Foundation
class WidgetData {
var id: Int64?
var name: String = ""
var entered : String = ""
var address: String = ""
var formid : Int64?
var formname : String = ""
var formdescription : String = ""
var formcategory : String = ""
init(id: Int64) {
self.id = id
}
init(formid: Int64) {
self.formid = formid
}
init(id: Int64, name: String, entered: String, address: String) {
self.id = id
self.name = name
self.entered = entered
self.address = address
}
init(formid: Int64, formname : String, formdescription : String, formcategory : String) {
self.formid = formid
self.formname = formname
self.formdescription = formdescription
self.formcategory = formcategory
}
}

Initializer for conditional binding must have Optional type, not 'Date'

Xcode is yelling error
But I don't know what happen. I've been searching and I think it might be something about casting and optional. The first one gives Initializer for conditional binding must have Optional type, not 'Date' and the second and third gives Initializer for conditional binding must have Optional type, not 'Double'
for article in (topic.articleArrays ?? nil)!{
if let articleId = article.id,
let articleHeadline = article.headline,
let articleSummary = article.summary,
let articleCity = article.city,
let articleState = article.state,
let articleDateretrieved = article.dateRetrieved,
let articlePublisher = article.publisher,
let articleLatitude = article.latitude,
let articleLongitude = article.longitude,
let articleRawBaseUrl = article.rawBaseUrl,
let articleRawUrl = article.rawUrl {
editedArticles?.append(NewsArticle(id: articleId, headline: articleHeadline, publisher: articlePublisher, summary: articleSummary, rawUrl: articleRawUrl, rawBaseUrl: articleRawBaseUrl, retrieved_date: articleDateretrieved, city: articleCity, state: articleState, latitude: articleLatitude, longitude: articleLongitude))
}
}
The struct for ediedArticles is NewsArticle which I've listed below
struct NewsArticle {
var id: String
var headline: String
var publisher: String
var summary: String
var rawUrl: String
var rawBaseUrl: String
var retrieved_date: Date
var city: String
var state: String
var latitude: Double
var longitude: Double
init(id: String, headline: String, publisher: String, summary: String, rawUrl: String, rawBaseUrl: String, retrieved_date: Date, city: String, state: String, latitude: Double, longitude: Double) {
self.id = id
self.headline = headline
self.publisher = publisher
self.summary = summary
self.rawUrl = rawUrl
self.rawBaseUrl = rawBaseUrl
self.retrieved_date = retrieved_date
self.city = city
self.state = state
self.latitude = latitude
self.longitude = longitude
}
}
topic.articlesArray have different data structure type which is SavedArticle (CoreData)
var articleArrays: [SavedArticle]? {
return self.articles?.allObjects as? [SavedArticle]
}
and have SavedArticle-CoreDataClass
var dateRetrieved: Date {
get {
return retrieved_date as Date
}
set(newDate) {
retrieved_date = newDate as NSDate
}
}
// TODO: Figured it out how to stored corrdinates in [Double]
convenience init?(id: String, headline: String, publisher: String, summary: String, retrieved_date: Date, city: String, state: String, latitude: Double, longitude: Double) {
guard let context = NaberCoreDataHandler.sharedInstance.managedContext else { return nil }
self.init(entity: SavedArticle.entity(), insertInto: context)
self.id = id
self.headline = headline
self.publisher = publisher
self.summary = summary
self.dateRetrieved = retrieved_date
self.city = city
self.state = state
self.latitude = latitude
self.longitude = longitude
}
with a SavedArticle-CoreDataProperties of following
#NSManaged public var city: String?
#NSManaged public var headline: String?
#NSManaged public var id: String?
#NSManaged public var publisher: String?
#NSManaged public var rawBaseUrl: String?
#NSManaged public var rawUrl: String?
#NSManaged public var retrieved_date: NSDate
#NSManaged public var state: String?
#NSManaged public var summary: String?
#NSManaged public var latitude: Double
#NSManaged public var longitude: Double
#NSManaged public var topics: SavedTopic?
It would be awesome if someone can help me figured it out what's the problem. I've beent rying for the whole day and nothing helps. Thank you! :)
if let (and guard let) can only be used to unwrap optional values. You can either assign those values with regular let statements on a separate line, or just pass them into the function directly since they don't need to be unwrapped.
article.dateRetrieved, article.latitude, and article.longitude are not Optionals. They are not declared with ? after their type names, so they can never be nil. There is therefore no need -- and in fact it is an error -- to try to unwrap them with an "if let" statement.
Remove the three lines of code that the compiler is complaining about.
When you create the NewsArticle and append it to editedArticles, you can pass those properties of article directly to the constructor of NewsArticle.

In Swift, how can I quickly set my instance variables?

public class User {
var id: Int
var fb_id: String?
var first_name: String?
var last_name: String?
var age: Int?
var distance: Int?
var login_at_pretty: String?
var login_at: Int?
var profile: Profile?
init(id: Int, fb_id: String?, first_name: String?, last_name: String?, age: Int?, distance: Int?, login_at_pretty: String?, login_at: Int?, profile: Profile?){
self.id = id
if let fb_id = fb_id {
self.fb_id = fb_id
}
if let first_name = first_name {
self.first_name = first_name
}
if let last_name = last_name {
self.last_name = last_name
}
if let age = age {
self.age = age
}
if let distance = distance {
self.distance = distance
}
if let login_at_pretty = login_at_pretty {
self.login_at_pretty = login_at_pretty
}
if let login_at = login_at {
self.login_at = login_at
}
if let profile = profile {
self.profile = profile
}
}
}
Is this the quickest way to do it? I feel like I'm over typing.
For your class, you're doing a lot of if-let statements that don't provide anything useful. ie:
if let fb_id = fb_id {
self.fb_id = fb_id
}
fb_id and self.fb_id are optionals, so the binding isn't necessary. Just do:
self.fb_id = fb_id
On that note however, if you're not planning on subclassing, using a struct would provide a memberwise initializer automagically:
public struct User {
var id: Int
var fb_id: String?
var first_name: String?
var last_name: String?
var age: Int?
var distance: Int?
var login_at_pretty: String?
var login_at: Int?
var profile: Profile?
}
Check out Memberwise Initializers for Structure Types in the swift docs

Resources