How to create Singleton in swift with arguments - ios

I learn the Swift Language and i need to create a manager like a Parse sdk.
For exemple when you initialize your Parse in app you write
Parse.setApplication("...", applicationId:"...")
And later you can write code like this
Parse.doSomething()
The method doSomething() use initial context.
Can you show me in my class should look like? I try some singleton exemple, but a have MyClass.sharedAttribute.doSomething() in case

What you have shown is no indication of singletons whatsoever, it sounds and looks more like a static class with static members and properties:
class MyStatic {
static var appIdA : String?
class func setApplicationId(a : String) {
appIdA = a
}
class func doSomething() {
print(appIdA)
}
}
MyStatic.setApplicationId("blabla")
MyStatic.doSomething() // prints Optional("blabla")
Of course there is the possibility that internally the class is a singleton, but Parse does not seem to be one, just looking at the functions it exposes.
The code comments even state
/*!
The `Parse` class contains static functions that handle global configuration
for the Parse framework.
*/

Related

Use generic extended swift class in Objective-c

In my project i have many swift classes that extend generic classes. And Now i'm in a need to send data from objective-c class to these swift classes. Is there any possible way to do this ?
I have tried using #objc before class as shown below
but it didn't allow me to do this.
I followed this answer stack link. But i checked when i run my app with this code it dint create the variable in the Project-swift class as shown in below image
as the variable is not created here so it gives error while calling the variable in objective-c class.
Kindly help out with better solution.
I got my solution by creating another class which contain a protocol and i indirectly call the generic extended class.
class EntityDataTable :BaseData<EntitySw> {
}
this is the generic extended class
and the another class i made to indirectly access this class in objective-c is
#objc class EntityService : NSObject {
var entityProtocol:EntityDataProtocol?
override init() {
super.init()
entityProtocol = returnDataObject()
}
func returnDataObject() -> EntityDataTable {
return EntityDataTable()
}
}
#objc protocol EntityDataProtocol{
func addFromService(source: CWEntity)
func getAll() -> [EntitySw]
}
Then i imported the Project-swift.h file in objective c class and made the object of swift class

Why Can Singleton classes be used as regular classes

I was under the impression that the main reason for using singletons was to make sure that only one instance could be created in a program. I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.
In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.
What makes a singleton different than a regular class if it lets you create multiple instances?
// singleton class
class Car {
static let sharedCar = Car()
func run(){
print("Running")
}
}
// use
Car.sharedCar.run()
// other instances- I was expecting an error here
var jetta = Car()
jetta.run()
var cobalt = Car()
cobalt.run()
What am I missing here, can someone explain singletons?
I thought that the compiler wouldn't let you create instances of a singleton as if it would be a regular class.
There is no language feature called "singleton", it is an idiomatic pattern. If you leave your implementation of singleton open for instantiations from outside, there is nothing the compiler can do about that.
In the following code I have a singleton where I'm creating multiple instances of it and it behaves as a regular class, but for some reason I was expecting an error.
You should add a private init to make sure there are no external instantiations:
class Car {
static let sharedCar = Car()
func run(){
print("Running")
}
private init() {
}
}
Now you are the only one who can instantiate your class. Users of Car class outside of your code are forced to rely on sharedCar instance that you create for them.

Save EVObjects with CoreData

I need to save some data with CoreData. Generally thats not a problem at all. The problem is, that the data is created with EVReflection an therefore inherits the class EVObject. To save the gathered data to CoreData they have to also inherit NSManagedObject. The problem is that swift does not allow you to inherit multiple classes. Would appreciate any tips.
class Device : EVObject
{
var channel : [Channel] = [Channel]()
var name : String = ""
var ise_id : Int = 0
var unreach : Bool = false
var sticky_unreach : Bool = false
var config_pending : Bool = false
override internal func propertyMapping() -> [(String?, String?)] {
return [("name", "_name"), ("ise_id", "_ise_id"), ("unreach", "_unreach"), ("sticky_unreach", "_sticky_unreach"), ("config_pending", "_config_pending")]
}
}
You don't have to inherit. You can extend them. Example:
class User : NSManagedObject{
#NSManaged .....
}
//Extension
import EVReflection
extension User : EVReflectable { }
https://github.com/evermeer/EVReflection#extending-existing-objects
Note I'm not aware of EVReflection but I think this answer can generally apply.
Don't use multiple inheritance. Have two separate classes and a mechanism for creating/loading/updating one object from the other. Protocols may allow it to be done in a way that minimises translation boilerplate (possibly using valueForKey(_:) and setValue(_:forKey) if you can know the key names in a safe manner.
It may not even be even be necessary to have an NSManagedObject subclass but just have an instance of NSManagedObject in all your classes that is loaded/created/saved as necessary.
It depends on what functionality you want to use from EVReflection. Since NSManagedObject also has NSObject as it's base class you could use most functions by just setting NSManagedObject as your base class instead of EVObject.
The only thing you have to do is instead of calling EVObject functions directly, you have to implement the code snippets that are in that EVObject method. Almost any function there is just a convenience method that will call the corresponding EVReflection function.
If you have any questions in the future, then please also report this as an issue on GitHub.

Use Realm subclass as custom function parameter

I am using Realm and it has function that take as an argument a class inheriting from Object (not NSObject), e.g.
realm.objects(Class)
I want to make a function that also takes Class as parameter.
I want make function that will take a class and forward it to Realm's function. I tried something like this, but it doesn't work:
func test(type: AnyClass) {
let realm = ..
realm.objects(type)
}
The Swift compiler reports an error saying that it cannot cast from AnyClass to Object.Type
I found a similar question here: Pass a Swift class as parameter, and then call a class method out of it
But maybe there is a simpler solution that doesn't require protocol implementation for every class? I want the function to make the decision of what to do by itself depending on what class it receives.
I want it to look like realm.objects(Class).
You can use the same signature: objects declaration looks like this:
func objects<T: Object>(type: T.Type) -> Results<T>
So you need a generic function constraining the type to subclasses of Realm.Object:
func test<T: Object>(type: T.Type) {
let realm = ...
realm.objects(type)
}
Then, assuming that your class (MyClass in this sample) inherits from Realm.Object, you can call it like this:
class MyClass: Object {}
test(MyClass)
If your method takes an object of that type, you can infer the type:
func test<T: Object>(element: T) {
let realm = ...
realm.objects(T.self)
}

Declaring function usable throughout project

I am new to swift and I am trying to figure out how to add a function that could be usable throughout the entire project. A simple function like
func globalFunction() {
println("Global function!")
}
Then be able to call this function on any swift file within my project. Where would I declare this function?
Its just like in any programming language - declaring the function outside the class, something like:
class A
{
var a:Int
// you can call your global function here
}
class B
{
var b:Int
// and here
}
func flobalFunction()
{
println("Hello, I am a global function!")
}
Use static functions if you still want to bind the method to a class:
class myClass{
static func globalFunc() -> Void {
println("This is it")
}
}
myClass.globalFunc()
You can add a .swift file in your project and declare your functions. Functions declared in this file will be available in the same module.
By default, variables, constants, and other named declarations that
are declared at the top-level of a source file are accessible to code
in every source file that is part of the same module.
Taken from The Swift programming language, see section on Top-Level Code.
If it is a helper function, you can create a new Swift file, and place the function in it else place it in any class as:
Class HelperFunctionsClass() {
func anyFunction () {
//Your implementation of the function here
}
}
To use this, create an instance of the class in the place you would like to use it as:
var instanceOfHelperFunctionClass = HelperFunctionClass()
Now simply use this instance variable to use the function as:
insttanceOfHelperFunctionClass.anyFunction()

Resources