Class create an instance of itself - ios

I want an instance method of a class to create an instance of itself
and append it to an array.
I tried this:
var vampireArray: [Vampire] = []
class Vampire {
func createSelf() {
vampireArray.append(Vampire())
}
}
but I get a strange error on console like (lldb)
Any ideas why?

Even without knowing the context to this code, in general, creating and then appending an instance of a class to an array outside of the scope of the class is a bad idea.
Instead, try putting the line vampireArray.append(Vampire()) wherever you were originally planning to put createSelf().
If you wanted to stick with this route, it would seem like the method createSelf() should be a static method and var vampireArray: [Vampire] = [] should also be a static variable inside your class.
EDIT:
If all you want to do is keep track of the number of vampires, this could be a good solution:
class Vampire {
static var VampireCount = 0
init(){
Vampire.VampireCount += 1
}
}
Then, whenever you wanted to access the count, just use Vampire.VampireCount

Related

How to use a variable from a different class

I have a rather simple question. How can I use variables from different classes in dart?
class ContainsVariable {
var variable = 1;
}
class DoesNotContainVariable {
var useVariable = variable + 1; // This gives me an error saying:
// Undefined name 'variable'
}
Having their own scope is a very fundamental feature of classes in Object Oriented Programming, corresponding to OOP principles.
Also note that from your code, it seems that you have not properly understood the idea of instantiation in Object Oriented Programming, since you are trying to set an instance variable without instantiating the class. I highly suggest to look into this topic to gain more understanding.
That being said, there are most definitely many ways to achieve what you want. Since your code sample is very general, I'm not exactly sure what you are trying to do, so I'll provide 2 examples, which might be useful:
Option 1 - static member variable
You can make a static (class level) member, which will be the same for all objects.
class ContainsVariable {
static var variable = 1;
}
class DoesNotContainVariable {
var useVariable = ContainsVariable.variable + 1; // here, you are using a
// static (class) variable,
// not an instance variable.
// That is why you are using
// the class name.
}
Option 2 - instantiation
You can instantiate the class - by creating an object of that class - and access the member of that object. Notice that there is no static statement here.
class ContainsVariable {
var variable = 1;
}
class DoesNotContainVariable {
var instanceOfContainsVariable;
var useVariable;
DoesNotContainVariable(){ // this is a constructor function
var instanceOfContainsVariable = new ContainsVariable();
useVariable = instanceOfContainsVariable.variable + 1;
}
}

Calling Extension Method to new Class

I am new to ASP.NET MVC and even newer to Extension Methods.
I have an extension Method I wrote
public static string ExtensionMethod(this Extension extype)
{
switch (extype)
{
case Extension.ONE:
return "Object one string";
case Extension.TWO:
return "Object two string ";
case Extension.THREE:
return "Object three string";
default:
return "Any other string";
}
}
So basically what this does is compare selections that have been made in the view and changes the label to match what they selected. Easy Peasy.
Now they want their reciept to reflect that exact string. So I have a class that manages my e-mails but I can't figure out how to put the value in the class.
in my view I call
#Model.ViewModelReference.Extension();
this brings it in great, but I have no idea how to reference an extension class in another class
email.To = receiptInfo.EmailAddress;
email.From = "email address";
email.Subject = "Reciept";
var bodyFormat = new StringBuilder();
bodyFormat.AppendLine("*RECEIPT*\t");
bodyFormat.AppendLine("I want Object string to show up here");
EDIT
Thank you. I implemented it like this
bodyFormat.AppendLine(MyNameSpace.MyExtension.Extension());
but I am getting an argument error, and I am not 100% sure which argument I should put in it, or it it even needs one. If I don't add the () it throws a cannot convert to string error. through logic I put in extype but it doesn't like that either, says it doesn't exist in the current context.
You simply have to include the class that the extension method is in and the extension method will be available.
In you class that manages e-mails add:
using MyNameSpace.MyExtension;
Then to use it, just have something of type Extension and call ExtensionMethod() off of it. So it would look something like:
using MyNameSpace.MyExtension;
var myExtension = new Extension();
myExtension.ExtensionMethod()
You cannot simply call MyNameSpace.MyExtension.Extension(), you need an instance of MyExtension, which is why in my example I have myExtension variable.

The use of singleton class in objective c and swift

I have a project implemented in both Objective C and Swift classes and I need to have global variables to be shared among these classes .
I have two variables currentUsername and currentUsernumber , I need to use these two in each view in the project, what is the best way to implement that ?
I have tried to implement singleton class and here is my code :
class curentUserSingleton {
static var instance: curentUserSingleton!
var currentUsername: String = ""
var currentUsernumber: String = ""
// SHARED INSTANCE
class func sharedInstance(Name : String , Number : String) -> curentUserSingleton {
self.instance = (self.instance ?? curentUserSingleton(uName: Name , uNumber: Number))
return self.instance
}
// METHODS
init(uName : String , uNumber : String) {
self.currentUsername = uName
self.currentUsernumber = uNumber
}}
But I don't know how to use this class safely in the OC and Swift and I am a little confused since I get declaration errors when I use the class in my code!
Is this the right way to write a singleton class and how to call it in both languages ?
I'd be inclined to do something like:
class User: NSObject {
static let sharedInstance = User()
var name: String?
var number: String?
}
Then you can set and retrieve name and number like so in Swift:
User.sharedInstance.name = "Foo"
User.sharedInstance.number = "42"
print(User.sharedInstance.name)
print(User.sharedInstance.number)
Obviously, to access this from Objective-C .m file, you have to have to include the system generated header like so:
#import "ModuleName-Swift.h" // obviously, replace `ModuleName` with the name of your module
But then the syntax for setting and retrieving these properties is similar as it was in Swift:
[User sharedInstance].name = #"Foo";
[User sharedInstance].number = #"42";
NSLog(#"%#", [User sharedInstance].name);
NSLog(#"%#", [User sharedInstance].number);
To me it seems you do not need a singleton at all. I suggest you would be best of redesigning the architecture to have a user class that can store the information you are needing (and more if you finds the need in the future).
Then you could either pass that user object around between the view controllers as they need or perhaps easier define a currentUser property for the app delegate class.
That way each view controller can obtain the app delegate from the NSApp global reference to the application object and then get the current user object from there. With this pattern the app delegate acts as the globally accessible singleton you need without any need to manage it yourself.

Singleton in one line on Swift 2.0

Please help me with Swift,
I need singleton with can inheritance.
I can do like this
class A {
var defaultPort: Int
required init() {
self.defaultPort = 404
}
class var defaultClient: A {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: A? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = self.init()
}
return Static.instance!
}
}
but in swift 2.0 we can do like this
static let defaultClient = A() //self.init()
but it creates an instance of the class A any way.
How i can use like this self.init()
static let defaultClient = self.init()
in order to be able to inherit
UPD
best way for now
class A {
class func defaultClient() -> Self {
struct Static {
static var onceToken: dispatch_once_t = 0
static var instance: A? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = self.init()
}
return instance(Static.instance, asType: self)
}
}
here we need helper as
func instance<T>(instance: Any, asType type: T.Type) -> T {
let reurnValue = instance as! T
return reurnValue
}
because another way cast A to Self not exist, for now.
p.s. crazy swift way!
why i can not do instance as! Self
Your question isn't very clear. You're looking for something like the class constant solution posted in this answer, but which automatically uses "my own class" instead of explicitly creating an instance of a specific class... right?
That is, you want to turn this:
class Singleton {
static let sharedInstance = Singleton()
}
into this:
class Singleton {
static let sharedInstance = SomeMagicThing()
}
class SingletonSubclass {}
where SomeMagicThing automatically creates a Singleton instance when you call Singleton.sharedInstance, and a SingletonSubclass instance when you call SingletonSubclass.sharedInstance. Correct?
Sorry, that can't be done (as of Swift 2.1).
Part of your issue is that static and class mean two different things. The static modifier means that the declaration it modifies is associated only with a specific type declaration. So, the Singleton type owns a pointer to a specific object -- its subclasses don't inherit that pointer. (And if they did, would it point to the same object or a subclass-specific one?)
If you could create a class var or class let, that'd (in theory) give you the kind of dispatch/inheritance you want. But trying that gives you an error (emphasis mine):
class stored properties not yet supported in classes; did you mean static?
So it sounds like this sort of thing might show up someday.
Of course, the other side of the problem is finding a way to dynamically refer to the "current" type responsible for executing some statement. In the context of an instance method, you have self.dynamicType for such things... but there's no equivalent for classes. (Self is a type constraint, not an actual type.) This is a side effect of the type system in Swift being much more strict and static than that of Objective-C (for example, metatypes aren't just a special flavor of otherwise normal objects). File a bug if you'd like to see a change to that effect?

Associated type error: Cannot assign a value of type '[SpecificType]' to a value of type '[NameOfTypeAlias]'

I am trying to create a fairly generic UITableView implementation that can display different types of cells. I'm using associated types to specify the data source type, cell type, and so on. I have most of it working really well, but I am having some trouble subclassing the implementation. I'm showing the least amount of code I can below to get the point across.
Here's my high-level architecture:
protocol DGTableViewAble {
typealias DGTableViewItemType
...
var items: [DGTableViewItemType] { get set }
}
class DGTableView: UITableView, DGTableViewAble {
typealias DGTableViewItemType = User
var items: [DGTableViewItemType] = [] { ... }
}
class DGPostsTableView: DGTableView {
typealias DGTableViewItemType = Post
}
...
Things work great when I assign an array of User objects to any DGTableView instance. For example, this works great:
var users: [User] = [...]
var userTableView: DGTableView
userTableView.items = users
However, when I try this:
var posts: [Post] = [...]
var postsTableView: DGPostsTableView
postsTableView.items = posts
I get the error:
Cannot assign a value of type '[Post]' to a value of type '[DGTableViewItemType]'
It seems like the compiler has trouble determining the associated types as I have things set up. Any ideas why? Any suggestions on improving the architecture?
You're not inheriting from DGTableViewAble in your class interface for DGPostsTableView:
class DGPostsTableView: DGTableView, DGTableViewAble {
typealias DGTableViewItemType = Post
...
}
Post isn't declaring viewable protocol?
class DGPostsTableView: DGTableView, DGTableViewAble {
typealias DGTableViewItemType = Post
}
It will also have to conform to said protocol. Maybe marking the unneeded protocol components as optional could solve your issue?

Resources