Print `po` object description with println()? - ios

If I'm to do this:
class MyObject {
var name = "Something"
}
var myObject = MyObject()
And then in the console at runtime, po myObject, I get this:
0x00007fe1596ef890
(name = "Something")
In other words, it prints out the property values of every property in the object.
I want to replicate this behaviour using println, but doing println(myObject) just gives me:
MyApp.MyObject
How can I get it to print out the property values, the same it would if I were to use the po command.

If you make your class conform to the Printable protocol, a description computed property will be printed instead of the type name:
class MyObject: Printable {
var name = "Something"
var description: String {
return "MyObject(name = \(self.name))"
}
}
let myObject = MyObject()
println(myObject)
// MyObject(name = Something)
Alternately, you can use dump() instead of println() to dump an object's properties using Swift's reflection tools:
dump(myObject)
// ▿ __lldb_expr_920.MyObject #0
// - name: Something

Related

Can't perform methods of objects stored in Array[Any]

I want to store objects of different types in an array.
The program below is only a minimum demo. In the anyArray:[Any] an instance of Object1 is stored. The print statement prints out the expected object type. In the following line the test of the stored object's type returns true. This means, during run time the correct object type is known and every thing seems to be fine.
class Object1 {
var name = "Object1"
}
var anyArray:[Any] = [Object1()]
print("\(type(of: anyArray[0]))")
let testResult = anyArray[0] is Object1
print("Test result:\(testResult)")
//print("Name:\((anyArray[0]).name)")
Console output:
Object1
Test result:true
However, if I try to print out the name property of the object, I get an error message from the editor:
Value of type 'Any' has no member 'name'
Well, at compile time the object's type is unknown. That's why the compiler complains. How can I tell the compiler that it is OK to access the properties of the stored object?
The difference comes from the difference from Type Checking in:
runtime, or
compile time
The is operator checks at runtime whether the expression can be cast to the specified type. type(of:) checks, at runtime, the exact type, without consideration for subclasses.
anyArray[0].name doesn't compile since the Type Any doesn't have a name property.
If you're sure anyArray[0] is an Object1, you could use the downcast operator as!:
print("\((anyArray[0] as! Object1).name)")
To check at runtime if an element from anyArray could be an Object1 use optional binding, using the conditional casting operator as?:
if let:
if let object = anyArray[0] as? Object1 {
print(object.name)
}
Or use the guard statement, if you want to use that object in the rest of the scope:
guard let object = anyArray[0] as? Object1 else {
fatalError("The first element is not an Object1")
}
print(object.name)
If all objects in your array have a name property, and you don't want to go through all the hoops of optional binding repeatedly, then use a protocol. Your code will look like this:
protocol Named {
var name: String {get set}
}
class Object1: Named {
var name = "Object1"
}
var anyArray:[Named] = [Object1()]
print("\(type(of: anyArray[0]))")
let testResult = anyArray[0] is Object1
print("Test result:\(testResult)")
print("Name:\(anyArray[0].name)")
Notice that anyArray is now an array of Named objects, and that Object1 conforms to the Named protocol.
To learn more about protocols, have a look here.
You object is still of type Any. You just checked if it can be of type Object1, but you did not cast it. If you want the object as Object1, you need to cast it.
Also if multiple classes can have name, you need to use Protocol like #vadian has mentioned in his comment and cast it to that protocol.
protocol NameProtocol {
var name: String {get set}
}
class Object1: NameProtocol {
var name = "Object1"
}
if let testResult = anyArray[0] as? NameProtocol {
print(testResult.name)
}
Edit: "I want to store objects of different types in an array". The solution that you have marked as correct will not work if all the objects that you have do not conform to the protocol.

What's the difference between : and = in swift

Sorry if the title is rather confusing, but I'm curious to know the difference between these two lines:
var title = String()
var title: String
Is one being initialized and one only be declared? Which is more correct?
For example, if I have a struct should I use one of the other?
So the reason I ask this is because I'm learning about how to grab some JSON from a url and then display it in my app. One of the new ways of doing so is using Decodable. So, I have a struct in a model class like so:
struct Videos: Decodable {
var title = String()
var number_of_views : Int
var thumbnail_image_name: String
var channel: Channel
var duration: Int
}
In another class I have this:
URLSession.shared.dataTask(with: url){(data,response,error) in
if(error != nil){
print(error!)
return
}
guard let data = data else { return }
do{
self.Videos2 = try JSONDecoder().decode([Videos].self, from: data)
//self.collectionView?.reloadData()
}catch let jsonErr{
print(jsonErr)
}
}.resume()
So, should I declare or initialize the variables in my struct? I'm assuming I should just declare them like so:
var title: String?
Would that be the correct syntax in my struct?
UPDATE:
I understand this question was more broad then I originally proposed it to be. I'm sorry about that, but thank you so much for all your great answers that clarified a lot up for me.
The difference is that : defines the type of your variable, whereas = assigns an actual value to the variable.
So:
var title = String()
This calls the initializer of the String type, creating a new String instance. It then assigns this value to title. The type of title is inferred to be String because you're assigning an object of type String to it; however, you could also write this line explicitly as:
var title: String = String()
This would mean you are declaring a title variable of type String, and assigning a new String to it.
var title: String
This simply says you're defining a variable of type String. However, you are not assigning a value to it. You will need to assign something to this variable before you use it, or you will get a compile error (and if this is a property rather than just a variable, you'll need to assign it before you get to the end of your type's init() method, unless it's optional with ? after it, in which case it gets implicitly initialized to nil).
EDIT: For your example, I'd probably declare all the variables using let and :, assuming that your JSON provides values for all of those properties. The initializer generated by Decodable should then set all the properties when you create the object. So, something like:
struct Videos: Decodable {
let title: String
let number_of_views : Int
let thumbnail_image_name: String
let channel: Int
let duration: Int
}
This initializes a value
var title = String()
This declares a value but does not initialize it
var title: String
If you attempt to use the latter, such as print(title), you will get a compiler error stating Variable 'title' used before being initialized
It does not matter whether the value is a class or a struct.
The = operator is the assignment operator, it assigns a value to the object on the left of the =
Typically, class or struct properties are declared but not initialized until the init() is called. A simple class might be
class MyClass {
let myProperty: String
init(aString: String) {
self.myProperty = aString
}
}
Whereas inside the scope of a function you may declare a local variable that only lives inside the scope of the function.
func doSomethingToAString(aString: String) -> String {
let extraString = "Something"
let amendedString = aString + extraString
return amendedString
}
In your specific example, the struct synthesizes an initializer that will allow you to initialize the struct with all the values needed to fill your properties. The initializer generated by Decodable should then set all the properties when you create a Videos struct, you will do it something like:
let aVideos = Videos(title: "My Title", number_of_views: 0, thumbnail_image_name: "ImageName", channel: Channel(), duration: 10)
Is one being initialized and one only be declared?
Yes, meaning that the declared cannot be used. If you tried to set a value for it, you would get a compile-time error:
variable 'title' passed by reference before being initialized
Which is more correct?
There is no rule of thumb to determine which is more correct, that would be depends on is there a need to initialize title directly.
On another hand, when it comes to declare properties for a class, saying var title = String() means that you are give title an initial value ("") which means that you are able to create an instance of this class directly, example:
class Foo {
var title = String()
}
let myFoo = Foo()
However, if title declared as var title: String, you will have to implement the init for Foo:
class Foo {
var title: String
init(title: String) {
self.title = title
}
}
let myFoo = Foo(title: "")
Also, you have an option to declare it as lazy:
lazy var title = String()
which means:
A lazy stored property is a property whose initial value is not
calculated until the first time it is used. You indicate a lazy stored
property by writing the lazy modifier before its declaration.
Properties - Lazy Stored Properties

How to get method for class in Swift

I have a class:
class myObject: NSObject {
dynamic var objectId : String?
dynamic var name : String?
dynamic var lastName : String?
dynamic var age : String?
}
In my other class I am getting the value of this class's property:
self.myArray.append(myObject.name!)
I can get the value of myObject.name by adding .name but what if there will be hundreds of properties in my myObject class? For that I want to create a method which can return the properties of my class using a variable:
let myVar = "name"
self.myArray.append(myObject.myVar)
It should append the values of property name, but I am getting an error:
value of myObject has no member `myVar`
and I know why I am getting the error.
How can I get access to properties of my class using a variable? Something like :getValue(String) should return that property of my class.
You should also have a look at NSMutableDictionary, here's a quick example which shows how it works
// initialise a dictionary
var dict = NSMutableDictionary(objects: ["first", "second", 42], forKeys: ["String1", "String2", "Int1"])
// add a new attribute
dict.addEntriesFromDictionary(NSDictionary(object: "New thing", forKey: "String3") as [NSObject : AnyObject])
// access the data
let firstString = dict.valueForKey("String1")
let firstInt = dict.valueForKey("Int1")
// update the data
dict.setValue(99, forKey: "Int1")
let newValue = dict.valueForKey("Int1")
I can be wrong, but as I've already said in a comment, it would be better to use Dictionary and store values in it. Also if you want to access some values with a dot-notation, but still be able to get them by string, you can just create a property and override setter and getter
class MyClass {
var properties = [String: AnyObject]()
var someProperty: String? {
get {
return properties["someProperty"] as? String
}
set {
properties["someProperty"] = newValue
}
}
This way you are able to access value of someProperty both by object.someProperty and object.properties["someProperty"]
You can do it making array of object like following
var arrayOfObjects = [myObject]
and then set an objects values
var firstObject:myObject
myObject.name = "Your name"
myObject.age = "Your age"
...
then append first object to arrayOfObjects
arrayOfObject.append(firstObject)
and you can access it
print("First Object's name: \(arrayOfObjects[0].name)")

how to print value of object in an array in swift, not its location

I have a class that contains data on certain entrepreneurs in a separate swift file that is within the same project.
It looks like this:
class Entrepreneur:NSObject {
var name:String?
var netWorth = (0.0, "")
var company:String?
var summary: [String]
var age: Int?
override init() {
name = ""
company = ""
summary = [""]
age = 1;
}
In the same file I have a function that returns an NSMutableArray which contain the instances of the entrepreneur class like this:
func populateArray() -> NSMutableArray {
var entreprenuersArray: NSMutableArray = []
//Mark Zuckerberg
let markZuckerBerg = Entrepreneur()
markZuckerBerg.name = "Mark Zuckerberg"
markZuckerBerg.age = 19
markZuckerBerg.company = "Facebook"
markZuckerBerg.netWorth = (35.7, "Billion")
// add mark zuckerberg object to array
entreprenuersArray.addObject(markZuckerBerg)
print (entreprenuersArray)
in my ViewController.swift file I create a constant called entrepreneurss and give it a type of the class "Entrepreneur" created above and initialize it like so:
let entrepreneuerss:Entrepreneur = Entrepreneur()
I then access one the class methods, the "populateArray" function and try to print the entrepreneurss array like so:
entrepreneuerss.populateArray()
print (entrepreneuerss)
The issue is the print function is printing the location of the object and not the value...something like this: .Entrepreneur: 0x7f88d0e3ecc0>"
What do I need to do so that I can return an array of the object values and not the location. I want to be able to access the array of object from my ViewController.swift file and randomly select an object and access its properties.
First, you have a instance method which returns an array of Entrepreneur objects (by the way, I don't see a return, maybe you forgot to copy it).
This method should be a class method, because you don't use any property of the Entrepreneur object which returns it :
class func populateArray() -> [Entrepreneur] {
var entreprenuersArray:[Entrepreneur] = []
//Mark Zuckerberg
let markZuckerBerg = Entrepreneur()
markZuckerBerg.name = "Mark Zuckerberg"
markZuckerBerg.age = 19
markZuckerBerg.company = "Facebook"
markZuckerBerg.netWorth = (35.7, "Billion")
// add mark zuckerberg object to array
entreprenuersArray.append(markZuckerBerg)
print (entreprenuersArray)
return entreprenuersArray
}
Then you can have your array by calling :
let array = Entrepreneur.populateArray()
Secondly, in this method, you create an array of Entrepreneur object and returns it, but in your example code, you never use this array :
// Creates a Entrepreneur object with default values
let entrepreneuerss:Entrepreneur = Entrepreneur()
// create an array of entrepreneurs objects, returns it, but never use it
entrepreneuerss.populateArray()
// print some information about the object with default values
print (entrepreneurs)
Instead, you should use the class method and try:
// create an array of entrepreneurs objects, returns it,
let arrayEntrepreneurs = Entrepreneur.populateArray()
// print some information about the array of Entrepreneurs objects
print (arrayEntrepreneurs)
In order to have a detailed description of your object, since it inherits from NSObject, just override the description read-only property in order to customize the text when you log your object :
override var description : String {
get {
return "Entrepreneur : name : `\(name) - company : `\(company)` - summary : `\(summary)` - age : `\(age)`"
}
}
Thus your print function will return :
[Entrepreneur : name : `Optional("Mark Zuckerberg") - company : `Optional("Facebook")` - summary : `[""]` - age : `Optional(19)`]
Maybe I am missing something here, but you can just use...
dump(arrayEntrepreneurs)
for Cocco
Swift.dump(arrayEntrepreneurs)
try
for element in array {
print(element)
}
What do I need to do so that I can return an array of the object values and not the location. I want to be able to access the array of object from my ViewController.swift file and randomly select an object and access its properties.
You already have the all the objects of entrepreneuers which are populated from your another swift file. you may use any object from the array and print it's any property.
Still you want to print the value of all the objects or all the properties of a object then you need to override the property called "description" into your model class.
add below code to your Entrepreneur class
override var description:String {
return "name :\(self.name) \n company \(self.company)"
}
The above code will print the name and company of any object of Entrepreneur

Extra Argument in call when creating and calling a class initialiser and passing in the literal values Swift

I have a small problem in swift. Let's say I have a class called Pet.
Pet has a variable for name and noise, created like so:
class Pet
{
var name : String = ""
var canMakeNoise : Bool = true
}
Now, when I call initialise the class creating let's say a cat, I can easily do it like so:
var cat: Pet()
cat.name = "Garfield"
cat.canMakeNoise = false
This works smoothly, however when trying to pass it in directly using literal values like so:
let cat : Pet("Garfield",true)
or
let cat : Pet(name:"Garfield",canMakeNoise:true)
I get this error:
Swift Compile Error - Extra Argument in call
Why is that? How can I fix it? Thanks in advance.
If you want to add arguments to the initializer than you need to specify a new init function instead of relying on the default one. Here's how you'd do it in your case:
class Pet {
var name : String = ""
var canMakeNoise : Bool = true
init( name : String, canMakeNoise : Bool ) {
self.name = name
self.canMakeNoise = canMakeNoise
}
}
var kitty = Pet(name: "Cat", canMakeNoise: true)
Since you use default values for your variables, xCode does not find a need for initializer. So when you create a new instance of the class it will be a Pet with name = ”” and canMakeNoice = true.
If you want to change these default values you will need to supply a init method (and you can than remove these default values)
class Pet{
var name:String
var canMakeNoise:Bool
init(name:String, canMakeNoise:Bool){
self.name = name
self.canMakeNoise = canMakeNoise
}
convenience init (name:String){
self.name = name
self.init(name:name, canMakeNoise: true)
}
}
I’ve supplied two init methods here. The first one takes 2 arguments:
var cat: Pet = Pet(name: "Kitten", canMakeNoise: true)
This will create a Pet with the supplied name and the supplied canMakeNoise.
If you want to you can also supply a convenience init This is a shortened init. In this case used to be able to make another instance of the Pet class.
var dog: Pet = Pet(name: "Doggy")
As you see we don’t supply the canMakeNoise property here cause the convenience initializer does that for us (and uses true as the canMakeNoice)

Resources