while calling an error is coming like Use of undeclared type 'district' - ios

struct District {
var district:[String]=["districtName","headQuarters"]
}
var telangana:[district] = ["rangareddy","shamshabad","suryapet","suryapet"]
print(telangana)

I think you're trying to create struct District with districtName and headQuarter as its properties,
struct District {
let districtName: String
let headQuarter: String
}
Now, you can create an array of District like so,
let telangana: [District] = [District(districtName: "rangareddy", headQuarter: "shamshabad"), District(districtName: "suryapet", headQuarter: "suryapet")]
print(telangana)

Your struct name is "District" so it should be:
var telangana:[District] = ["rangareddy","shamshabad","suryapet","suryapet"]
Although this will not compile because an array or Districts cannot be initialised with [String]
You should try something like:
let district1 = District(district:[""rangareddy","shamshabad","suryapet","suryapet""])
var telangana:[District] = [district1]

Create first property in your struct
struct District {
var districtName: String
var headQuarters: String
}
then create array of struct
var telangana: [District] = []
telangana.append(District(districtName: "rangareddy", headQuarters: "shamshabad"))
print(telangana)

Related

App crashes when I am trying to saved data in my model

I am developing an App using Realm. At some point in my app when I try to manipulate my model, my app crashed in an unexpected way. Here is what the stack trace said
Can only add, remove, or create objects in a Realm in a write transaction - call beginWriteTransaction on an RLMRealm instance first
What I am trying to do :
lets break down my problem in parts.following is my model of app
#objcMembers public class ClassGroup : Object , Codable {
dynamic var Id : Int? = ""
dynamic var ClassName : String? = ""
dynamic var TeacherId : Int = 0
dynamic var Teachers : [TeacherMdoel]? = []
}
#objcMembers public class TeacherModel : Object , Codable {
dynamic var Id : String? = ""
dynamic var Name : String? = ""
dynamic var ClassId : Int = 0
dynamic var Students : [StudentClass]? = []
}
#objcMembers public class StudentModel : Object , Codable {
dynamic var Id : String? = ""
dynamic var Name : String? = ""
dynamic var ClassId : Int = 0
dynamic var TeacherId : Int = 0
}
now I am trying to get the list of all classes like this from realm (after saving them to realm )
let mClassLists = mDbHelper.realmObj.objects(ClassGroup.self)
Now here I get exception/error. What I am doing is, I am trying to populate my UITableView with some data that consist of all of the above models. I am fetching data and saving them in my model and trying to supply that list to UITableView but my app crash with the error I mentioned above
let mClassLists = mDbHelper.realmObj.objects(ClassGroup.self)
let classLists = Array (mClassLists)
for classModel in classLists {
let resultPredicateTeachers = NSPredicate(format: "ClassId == %#", classModel.Id)
let mTeachersList = mDbHelper.realmObj.objects(TeacherModel.self).filter(resultPredicateTeachers)
if(mTeachersList.count > 0){
var listTeachers : [TeacherModel] = []
for teacherModel in mTeachersList {
let resultPredicateStudent = NSPredicate(format: "TeacherId == 29")
let mStudentList = mDbHelper.realmObj.objects(StudentModel.self).filter(resultPredicateStudent)
if(mStudentList.count > 0){
let studentsList = Array(mStudentList)
teacherModel.Students = studentsList[0]
}
listTeachers.append(savedDetailItem)
}
classModel.Teachers? = (listTeachers)
listClassModel.append(classModel)
}
}
**In the Above code you can see that I am gathering data on behalf of Ids and saving the resultant arrays in the model. So I am getting error in the following line
**
teacherModel.Students = studentsList[0]
now I really do not understand why it is happening? I am not saving data in realm, I am saving in my model, still I am getting error.
In Realm database, if you want to modify any model (save new data or update), the operation should be performed in a write transaction:
try! realm.write {
realm.add(<your_model_objects>)
}

How to populate a table view in a order based off an element from a class

I have the following structures and arrays for my data and for my table view cells:
struct CellData
{
var cell: Int! = 1
var SegueIdentiier: String!
var text: String!
var image: UIImage!
}
struct Course {
var isEmpty: Bool = true
var Title: String = String()
var FK: String = String()
var Subject: String = String()
var teacher_fk: String = String()
var teacher_name: String = String()
var grading_period: String = String()
var room: String = String()
var block_abbreviation: String = String()
var block: Int = 0
var parser: XMLParser!
}
var ArrayOfCellData = [CellData(), CellData(), CellData(), CellData(), CellData(), CellData(), CellData(), CellData()]
var Courses = [Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course(), Course()]
And when I parse an XML file the "block" is filled with a given number. Id like to populate my table view in order of these block numbers.
Ie if Courses[0].block = 4 and Courses[3].block = 2 id like to populate my table view in the order of Courses[3] then Courses[0].
I cant figure out how to do this for the life of me. This is my first time posting on Stackoverflow so please be nice! :)
One way to achieve the desired behaviour would be to sort your list of courses according to your desired sorting criteria.
Courses.sort {
$0.block < $1.block
}
You could also have a sorted copy of your list if the initial order is important for some reasons.
Edit - The other answer appears way simpler than mine, I'd totally go with that one haha. Though here is an example of looking up the documentation and working with what it tells you!
You need to sort your arrays. The indexPath of your cells needs to be able to uniquely determine the index of your array for your data to generate the cell, so you want your array to be sorted before you load the table.
You'll need to write a custom sort function for this, but it should be very easy: https://developer.apple.com/reference/foundation/nsarray/1408213-sortedarray
Your sort should look something like this:
func intSort(course1:Course, course2:Course, void *context) -> NSInteger
{
int v1 = course1.block;
int v2 = course2.block;
if (v1 < v2)
return NSOrderedAscending;
else if (v1 > v2)
return NSOrderedDescending;
else
return NSOrderedSame;
}
You may ned to pass the courses as Any and cast them to Courses in the function, but this should get you started.

Cannot add an append an array into a dictionary that has an empty array

I have a Profile Data singleton class as follows.
I am trying to store data into an empty array in a dictionary .
After appending data to the array also the count of the array is 0.
class ProfileData{
static let sharedInstance = ProfileData()
var artistProfileDict = [String : Profile]()
var loggedInUserProfile = Profile(artistName: "John Smith", artistDescription: "Admiral of New England, English soldier, explorer, and author.", totalLikes: "174", totalViews: "200", totalFollowing: "100",totalFollowers:"50",imageUrl:"image_singer", feeds:[] )
private init() {
getProfilesDictionary()
}
func getProfilesDictionary()->[String: Profile]{
artistProfileDict["John Smith"] = loggedInUserProfile
return artistProfileDict
}
func add(array: Feed, artistName: String) {
artistProfileDict[artistName]!.feeds.append(array)
}
}
In another view Controller I am trying to add an array to the empty array in the dictionary as follows
let newFeed = Feed(profilePicture: "image",artistName: "New",
videoUrl: "url",videoTitle:"New", videoViews: "160",likes:
"200",shoutouts: "200",comments: [],votes: "50", dateCreated: Date(),
userActivity :"This user liked your video")
ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")
After appending the array to the empty array in the dictionary I still get the count of the array as 0.
I am not able to figure out the problem here. Any help will appreciated . Thank you.
Profile class
struct Profile {
var artistName: String
var artistDescription: String
var totalLikes: String
var totalViews: String
var totalFollowing: String
var totalFollowers: String
var imageUrl: String
var feeds : [Feed]
init(artistName: String,artistDescription:String,totalLikes:String,totalViews:String,totalFollowing:String,totalFollowers:String,imageUrl:String, feeds:[Feed]) {
self.artistName = artistName
self.artistDescription = artistDescription
self.totalLikes = totalLikes
self.totalViews = totalViews
self.totalFollowing = totalFollowing
self.totalFollowers = totalFollowers
self.imageUrl = imageUrl
self.feeds = feeds
}
}
It's working fine
ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")
ProfileData.sharedInstance.artistProfileDict["John Smith"]?.feeds.count // 1
Probably you are using wrong class ArtistProfileData instead of ProfileData.

How to Deal with Default Initializer when variable are not initialized Using Struct

I'm using swift struct and trying to use its default initializer when my struct variables are not initialize, I try both non-optional and optional variables but in its only showing "memberwise Initializer".
below is example with optional variables
struct myFirstStruct {
var value1:String?
var value2:String?
}
below is example with non-optional variables
struct myFirstStruct {
var value1:String
var value2:String
}
and it only gives
myFirstStruct(value1: <#String?#>, value2: <#String?#>)
and i want to use myFirstStruct()
help me. :)
Xcode is only showing you the 'member-wise' initialiser, but it's perfectly valid to use myFirstStruct(), passing no arguments, because all your variables have default values.
struct myFirstStruct {
var value1:String?
var value2:String = "InitialString"
}
let s1 = myFirstStruct()
// value1 = nil, value2 = "InitialString"
let s2 = myFirstStruct(value1: "Hello", value2: "World")
// value1 = "Hello", value2 = "World"
Need to set default value.
struct myFirstStruct {
var value1:String? = nil
var value2:String? = nil
}
let object = myFirstStruct()

Swift Dictionary with Array Values

If I declare a class property as:
var list = Dictionary<String, StructType[]>()
and then try to add a value from within a class method with:
var structType = StructType()
list[ "A" ] = [ structType ]
I get a runtime EXC_BAD_INSTRUCTION error. However, if I declare the dictionary within the class method and add a value there is no error.
It has something to do with the dictionary having values which are arrays. If I change the declaration to something simpler, like:
var list = Dictionary<String, String>()
then within the class method:
list["A"] = "some string"
works without any issues.
Any ideas?
UPDATE:
I've also tried declaring:
var list = Dictionary<String, String[]>()
and there is no issue referencing the list within a class method.
list[ "A" ] = [ "String1", String2" ]
Also the class declaration:
var list = Dictionary<String, SomeStruct>()
can be referenced within a class method.
UPDATE 2:
The struct is defined as:
struct Firm {
var name = ""
}
If you create your list and class in the following way it should work fine:
struct StructType {
var myInt = 0;
}
class MyClass {
var list = Dictionary<String, StructType[]>()
func myFunc () {
var structType = StructType()
list[ "A" ] = [ structType ]
}
}
var a = MyClass()
a.myFunc()
The following code appears to work for me in a playground.
struct StructType {
}
var list = [String:[StructType]]()
var structType = StructType()
list["A"] = [structType]

Resources