Search Your Question

Write a program to remove duplicate elements from array

Ans : 


    Method - 1 : 

    extension Array where Element: Equatable {
        mutating func removeDuplicates() {
            var result = [Element]()
            for value in self {
                if !result.contains(value) {
                    result.append(value)
                }
            }
            self = result
        }
    }


   Use : 


var faa = [3, 0, 1, 0, 3, 1, 2, 0, 1, 2]
faa.removeDuplicates()

output = [3,0,1,2]


Method - 2


 let unique = Array(Set(originals))

Set is collection of unique and unordered elements. So we have converted array to set here to remove duplicate. Output array does not have same order as original.


Write a program to find first 10 prime numbers

Ans : 


     let N = 10
    let maxP = 1000
    var isPrime: [Bool] = []
    var primes: [Int] = []
    
     for i in 0...maxP {
        isPrime.append(true)
    }
    
    isPrime[0] = false
    isPrime[1] = false
    
     for i in 2...maxP {
       if isPrime[i] == true {
          var j = i*i
          while j <= maxP 
               isPrime[j] = false
               j += i
          }
          primes.append(i)
       }
    }
    
    for i in 0..<N {
        print(primes[i])
    }

Delete record from Core-data

Ans: 

Deleting a record from a persistent store involves three steps:

  1. Fetch the record that needs to be deleted
  2. Mark the record for deletion
  3. Save the changes
Code : 


let fetchRequest: NSFetchRequest<Profile> = Profile.fetchRequest()
fetchRequest.predicate = Predicate.init(format: "profileID==\(withID)")
let objects = try! context.fetch(fetchRequest) // Step 1
for obj in objects {
    context.delete(obj)  // Step 2
}

do {
    try context.save() //  <- remember to save data // Step 3
} catch {
    // Do something... 
}

Difference between Core Data and Sqlite

Ans : Core-data is not database that we understand. Sqlite is Database. 

Lets have a look over difference between Core-data and Sqlite (or Database) :

Core Data:


  1. Primary function is graph management (although reading and writing to disk is an important supporting feature).
  2. Operates on objects stored in memory (although they can be lazily loaded from disk).
  3. Works with fully-fledged objects that self-manage a lot of their behavior and can be sub classed and customized for further behaviors.
  4. Non-transactional, single threaded, single user (unless you create an entire abstraction around Core Data which provides these things).
  5. Only operates in memory.
  6. Requires a save process.
  7. Can create millions of new objects in-memory very quickly (although saving these objects will be slow).
  8. Leaves data constraints to the business logic side of the program.


Database or SQLite:


  1. Primary function is storing and fetching data.
  2. Operates on data stored on disk (or minimally and incrementally loaded).
  3. Stores "dumb" data.
  4. Can be transactional, thread-safe, multi-user.
  5. Can drop tables and edit data without loading into memory.
  6. Perpetually saved to disk (and often crash resilient).
  7. Can be slow to create millions of new rows.
  8. Offers data constraints like "unique" keys.
Credit : http://www.cocoawithlove.com/2010/02/differences-between-core-data-and.html


difference between coredata and sqlite

Advantage of Core-data : 

  • Much better memory management. With a plist you must load the entire thing into memory; with Core Data only the objects you're currently using need to be loaded. Also, once objects are loaded, they're normally placeholder "fault" objects whose property data doesn't load until you need it.
  • Related to the above, when you have changes, you can save only the changed objects, not the entire data set.
  • You can read/write your model objects directly instead of converting them to/from something like an Dictionary.
  • Built-in sorting of objects when you fetch them from the data store.
  • Rich system of predicates for searching your data set for objects of interest.
  • Relationships between entities are handled directly, as properties on the related objects. With a plist you would need to do something like store an object ID for a relationship, and then look up the related object.
  • Optional automatic validation of property values.
More about Core-data : 

  • CoreData isn't a Database. It's an object persistence layer. There is no concept of primary keys or foreign keys in CoreData.
  • If you want to establish a relationship between two entities. You'll define a relationship, CoreData takes care of how that relationship is stored.
  • Select an entity, use plus button at the bottom of the entities attributes list, select add relationship, select the destination entity from the dropdown.
  • Select the destination entity and define an inverse relationship in the same way.

What is lazy property?

Ans : 

When to use lazy initialization is when the initial value for a property is not known until after the object is initialized.

For example, if you have a Person class and a personalizedGreeting property. The personalizedGreeting property can be lazily instantiated after the object is created so it can contain the name of the person.

class Person {      
  var name: String
    
  lazy var personalizedGreeting: String = {
    return "Hello, \(self.name)!"
  }()
    
  init(name: String) {
    self.name = name
  }
}

When you initialize a person, their personal greeting hasn’t been created yet:

let person = Person(name: "John Doe") // person.personalizedGreeting is nil But when you attempt to print out the personalized greeting, it’s calculated on-the-fly:

NSLog(person.personalizedGreeting)

Bonus Tip : You do need to declare your lazy property using the var keyword, not the let keyword, because constants must always have a value before initialization completes.

Benefit of lazy property increase performance in terms of speed.