Different types of the same object - iphone

So, I'm in Xcode and programming a small program from a friend.
I want to initialize several instances of an object, put them in an array and then iterate through it (via a function that returns a string). Each object adds some text to that string when it's iterated, depending on the variables of the object.
Let's say the class is Tree. The variables in the class are name (string), height(int) and a hasLeaves(bool)(weather it currently has leaves on it or not). I could easily print:
"This is a name that is height meters tall and has leaves.
The problem is that I want the string to be a bit different, depending on which kind of tree it is. Like this:
The oak(name) is big and lifeful, it's height meters tall and has leaves.
Apple trees(name) carries some apples, it's height meters tall and has leaves.
If you ever visit Sweden you should check out the firs(name), they are height tall and haven't got leaves.
I don't want you to write the code for me, but give me a clue. I don't know what to look for. I was thinking about creating a subclass for each Tree, but every subclass would only appear once in the program and I don't know if it's necessary or not.
As you recognize, I'm having a hard time even formulating this question, but if you understand my intentions I'm glad for any clue I can get.
Edit: So this is my attempt to show it in code:
Class:
class tree {
var treeHeight: Int?
var treeWidth: Int?
var hasLeaves: Bool
var treeString: String
init (height: Int?, width: Int?, leaves: Bool, theString: String) {
self.treeHeight = height
self.treeWidth = width
self.hasLeaves = leaves
self.treeString = theString
}
}
Main function:
var oak: tree = tree(height: 1, width: 2, leaves: true, theString:"Oh, the mighty oak")
var appleTree: tree = tree(height: 1, width: 2, leaves: false, theString: "Yummy Apples")
var treeArray: Array = [oak, appleTree]
var resultString = "This is the stories of the trees: "
for tree in treeArray {
if tree.hasLeaves == true {
resultString = resultString + tree.theString
}
}
So, I want the string added to the "resultString" to be different, depending on what kind of tree it is, but I don't want to set that string in the initialization of the object, but rather from what "kind" of tree it is. Does that make it easier to understand?
I want the string (treeString) to be static depending on what "kind" of tree it is. So if it is an oak, the string is always "Oh, the might oak".

It sounds like you want a tree class with some properties like leaves, etc. Maybe you also want to subclass leaves with additional properties like color, etc. I recommend the WWDC 2014 video:
http://youtu.be/W1s9ZjDkSN0
Somewhere around 30 minutes they have a demo of a Car class with RaceCar at subclass.
Regarding creating the objects, you can build each object individually and then collect them in an array as one option. For example, maybe in a form on your app the user inputs data for a class or subclass and then you create an object, store to a master array which you then archive to a file.

So, if anyone stumbles in to this question, this is what I learned:
I was looking for subclasses and protocols. There are methods to determining whether an object is of a certain subclass, and in my case, I could have a protocol called "Tree" with certain methods and/or methods, and then make subclasses to this protocol, called "oak" and "fir".

Related

Returning variables from Model to other ViewControllers

I am making a weather application. I basically created a class where I will only get data from API and return them as needed. I have variables like cityName, currentWeather etc.
Problem is sometimes API doesn't provide them all so I need to check if they are nil or not before return them. What comes to my mind is set variables like this first:
private var cityNamePrivate: String!
and then
var cityNamePublic: String {
if cityNamePrivate == nil {
//
}
else { return cityNamePrivate }
But as you can as imagine, its very bad because I have a lots of variables. Is there any better logic for this? Should I just return them and check later in wherever I send them?
The problem here is that you will have many variables to deal with. It's not just returning them from the API, it's also dealing with them in your app and perhaps in some processing code.
One solution is to have a big class or struct with many properties. This will work very well, is straightforward to implement but will require lots of repetitive code. Moreover, it will require to change your API and all your code, whenever some new properties are made available by the remote web service.
Another approach is to have replace the big inflexible class or struct, with a dynamic container, e.g. an array of items [ Item ] or a dictionary that associates names to items [ String : Item ]. If the data is just strings, it's straightforward. If it's several types, you may have to have to implement a small type system for the elements. Example:
var x : [ String: String] = [:]
x["city"]="Strasbourg"
x["temperature"]="34°C"
struct Item {
var name : String
var value : String
}
var y : [ Item ] = [Item(name:"city",value:"Strasbourg"),
Item(name:"temperature", value:"34°C")]
The other advantage of this approach is that you stay loyal to the semantics: an information that is not available in the API (e.g. "unknown") is not the same as a default value. I.e. if the weather API does not return a temperature, you will not display 0 in your app. because 0 is not the same as "unknown". While strings are more robust in this matter, the absence of a name is not the same as an empty name.
This last remark suggests that in your current scheme, of having a big data transfer object, you should consider to keep the properties as optional, and move the responsibility for the processing of unknown data to your app.

what is the difference between a "var get return" statement over just a simple var

As a beginner I am just wondering why it would be benefitial to user this statement
//first statement
var email: String? {
get {
return emailField.text
}
}
over just this:
var email = emailField.text
I get it that the first code is instantiating the email variable outside a function , but I might as well just use the emailField.text throughout my code. Is this just a fance way of renaming the emailField.text to "email"? Or what is the deeper reason to create the first statement?
One important reason to use these "computed properties" is to use them exactly for what the name suggests: compute stuff that depends on something else, whenever it's needed.
Consider for example:
struct Rectangle {
var width: Double
var height: Double
var area: Double
}
Having an implementation like this forces you to make sure that whenever either width or height changes, you must remember to update area as well. Worse, what would happen if someone were to assign to area? You'd have no idea how to divide this value into width and height.
Computed properties come to the rescue:
struct Rectangle {
var width: Double
var height: Double
var area: Double {
return width * height
}
}
not only is it now impossible to forget updating area, it's also no longer assignable.
The first code example is a computed value as noted in the comments and since there is only a getter, the value can never be set meaning you couldn't, for example, write email = "new value".
The second example is a field and since it's a var you can read and write it. (I assume in your example it's a field and not just a local variable.)
Why is it beneficial? Depends on your use case. It's often desirable to make things immutable or to tightly control mutation. If this was a field on your class, you could write code in your class to modify the value of emailField.text but code outside of your class could be prevented from doing the same.
Perhaps you want to expose the value of what I assume is your text box to other parts of your program without also allowing them to mutate the value.

Communicating "which playing card" between View and Model - best way?

For fun I'm building a FreeCell solitaire game from scratch in Swift. I've got my model for the deck set up to build the deck and each Card struct has a suit, rank, and description (e.g., 4♠️) plus some other properties. The model for the game simply stores what cards are in what columns. A change in the view (moving a card) will alert the controller to modify what cards are in what columns.
When a user taps on the card (a subclass of UIView including a label that contains card.description) the label.text will be sent to the controller to identify the card in the model. I'm wondering what the best way to do this is.
The most obvious way I can think of is to build dictionary where the keys are descriptions and the values are cards. I can write a function in my DeckBuilder class to build the dictionary for me, of course. But since the description already exists as a property of the Card struct, this seems a little redundant and clunky-ish.
Another method would be to, every time a card is selected, iterate through the deck of cards in the model and say "if selectedCard.description == tryCard.description { //this is the right card! } " but that seems absurdly inelegant and theoretically too computationally expensive (although in reality I'm sure it takes no time at all).
What I'd love to do is have the controller say "get the Card that has this String as its description property." Similar to dictionary lookup, but without an actual dictionary.
Is this last solution possible? If not, what do you think is best?
Thankya!
You should not use the text of a label as an indication of a value at some location; this is like storing your model in your view. Instead you have come internal structure that represents the state of the columns. Each column can be an array of cards. The columns themselves can be in an array of columns:
struct Card {}
var deck = [Card]()
var columns: [[Card]] = [[Card]](repeating: [], count: 7)
deck.shuffle()
for i in 0..<columns.count {
for j in 0..<i {
columns[i].append(deck.draw())
}
}
Now if you have a click on a view. you just need to know what column and what index in that column was clicked (you can do this based on the frame of the view or by assigning a tag to each view). You can now get the value of the card but looking at the columns array: columns[selectedColumn][selectedRow]
I would create two enums, one for the rank and one for the suit.
enum Rank {
case value(Int)
case jack
case queen
case king
case ace
}
enum Suit {
case diamond
case heart
case spade
case club
}
This is way safer and more readable than a dictionary. In your struct Card you can add these two properties.
struct Card {
var rank: Rank
var suit: Suit
}
It's up to you if you want to compare the Strings, compare the enums or even have your Card struct conform to the Equatable protocol. I would probably go for the Equatable protocol but I do not think that there are big differences between these options.

Best practice for array as property in Swift

I have a model class in Swift, whose primary purpose is to contain an array of custom objects, but also has other methods/properties etc.
public class Budget: NSObject, NSCoding {
var lineItems : [LineItem] = []
// Other methods
// Other properties
}
As I understand it, it's best practice to not make the property publicly settable, but I want it to be testable, so lineItems needs to be publicly gettable.
Reading the docs, I could do this:
private(set) public var lineItems : [LineItem] = []
But then I have to write a lot of boilerplate code to recreate array methods, such as insert, removeAtIndex etc.
What is best practice here? At the moment, I don't need to do anything else on insert/removal of items, but I guess I may need to do validation or similar in future, but even so it seems redundant to have to write code that just recreates Array methods.
Would it be better just to make lineItems publicly gettable and settable? Are their circumstances where this would or wouldn't make sense?
Thanks!
Swift's Array is a (immutable) value type, which means that
var a = ["object"]
var b = [String]()
b.append("object")
b == a // true
From this point of view it does not make sense to allow modifying an array and not allow setting it - modifying is basically creating new array and assigning it to variable.

Shared (or static) variable in Swift

I have a class with an array which values comes from a text file. I would like to read this values once and store them in a shared variable, making possible other classes access that values.
How can I do that in Swift?
UPDATE:
Suppose I have three classes of animals and which of them can be found in a set of places which is load from differents tables (each animal have yours and the structure is different for each one). I would like to be able to use them linking to specific class:
clBirds.Places
clDogs.Places
clCats.Places
Note that I need to load data once. If I dont´t have a shared variable and need to put it outside the class, I need to have different names to the methods, just like:
BirdsPlaces
DogsPlaces
CatsPlaces
And we don´t have heritage in this case
Declare the variable at the top level of a file (outside any classes).
NOTE: variables at the top level of a file are initialized lazily! So you can set the default value for your variable to be the result of reading the file, and the file won't actually be read until your code first asks for the variable's value. Cool!
Similarly, you can declare an enum or struct at the top level of a file (outside any classes), and now it is global. Here's an example from my own code:
struct Sizes {
static let Easy = "Easy"
static let Normal = "Normal"
static let Hard = "Hard"
static func sizes () -> String[] {
return [Easy, Normal, Hard]
}
static func boardSize (s:String) -> (Int,Int) {
let d = [
Easy:(12,7),
Normal:(14,8),
Hard:(16,9)
]
return d[s]!
}
}
Now any class can refer to Sizes.Easy or Sizes.boardSize(Sizes.Easy), and so on. Using this technique, I've removed all the "magic numbers" and "magic strings" (such as NSUserDefault keys) from my code. This is much easier than it was in Objective-C, and it is much cleaner because (as the example shows) the struct (or enum) gives you a kind of miniature namespace.