Is type also object in Swift? and what's the meaning of sending a message to an object - swift

This might no be particularity a language related question. Since the Swift is the language I'm currently learning so I'm using it here.
I picked up this sentence from the Matt Neuburg's book iOS 10 Programming fundamentals with Swift
In Swift, "everything is an object" and an object
Object is something you can send a message to.
Let's add an example. Suppose there is a customer type called Dog. It has bark() and sit() function. Two instances of the type Dog named fido and rover had been initiated.
In swift, the syntax of message-sending is dot-notating, like
fido.bark()
rover.sit()
rover.printName()
The above code lines means sending message to object fido and rover
Question 1:
Why the description is: Sending message to object fido and rover? To me it looks like the object fido and rover sends out some message to print it out in the console (ex. printName() ) rather we sending message to it. .bark() looks like it will make fido to do something and shoot its reaction to the outer world, because bark() is the function inside its belly, not something we created and inject in to its body. we just inform this function its the time to work. Is this informing object to do a specific thing is the meaning of sending the message to the object?
Question 2:
"In Swift, everything is an object", an object is something you can send message to
If I understand correctly, even the object type itself is also an object. such as String, Int or Double. Because type has type properties which means you could send a message to it
Thanks a lot for your time

There is some debate within the OOP world about "message passing" versus "method calling," both in how we talk about them, and how they're implemented. In the prototypical OOP language (SmallTalk, which ObjC is a descendent of), everything really is a "message." I bundle up a message (which is a real data structure, NSInvocation in its most heavyweight form in Cocoa), and deliver it to the object's inbox, which then processes the message and performs some action.
Most common OOP languages didn't adapt this model (when something does today, we tend to call it "actor" rather than "object"). C++, which heavily inspired most of the current crop of "object-oriented" languages took a "method calling" approach. This is much more closely aligned with function calling, and has to do with jumping to a specific point in memory and executing instructions there. Method calling is more static than message passing. It is much easier at runtime to completely reconfigure how messages are handled, create new message handlers, re-route old message handlers, etc. Method calling is much faster.
In practice, there isn't a huge difference in most programs at most call sites. The vast majority of ObjC "messages" translate precisely 1:1 into a method call, and the system almost always avoids generating a full NSInvocation message (they're insanely expensive).
But we still conceptually mix the two ideas when we teach OOP, and that's what's happening here. (Swift also happens to employ both mechanisms heavily.)
A good way to think of fido.bark() is "send the bark message, with no parameters to fido." It is then up to Fido to decide what to do about that. In practice, messages are usually understood to be "commands" in that the object doesn't "decide" what to do. But in principle it might. For example, Fido might be a pretty smart dog, and decide not to bark because it's so late at night, even though you told him to, or maybe he's asleep and he doesn't like to bark then. The concept of objects is that they encapsulate that knowledge and state.
To your second question, in Swift types are not full objects. They're "metaobjects." You are absolutely right that you can send messages to them, and so they in some ways behave like objects. But Swift doesn't have "first class types," which means that not everything you can do with an object can be done with a type. But yes, you're definitely on the right road that in many cases you can treat a type as if it were an object.
(A major Swift feature request is to make types more first-class by adding a concept called Higher Kinded types. This would make it possible to write methods on Array itself, rather than only on Array<T>, and make some types, like Functor, possible to write at all.)

I was also reading a book < iOS 9 Programming Fundamentals with Swift >, there are some interesting aspects of looking at 'everything is object in swift'.
"In Swift, everything is an object", an object is something you can send message to
In swift, we can add extension for String, Int, Double...etc
for example.
extension Int {
func sayHello() {
print("Hello, I'm \(self)")
}
}
1.sayHello() // outputs: "Hello, I'm 1"
The 1 here is not a class or instance, it is a struct. Swift has three kinds of object type: classes, structs, and enums.

Related

Is there a standard protocol for Swift class/struct with an empty initializer

I'm curious, is there a pre-existing protocol whose only requirement is that there be an init with no arguments? I'm creating a generic that needs to be able to initialize an associated type without worrying about any arguments. This seems to call for a protocol like this:
protocol HasEmptyInitializer {
init()
}
It seems like a pretty basic protocol that might be needed in many contexts. Before I go polluting my protocol space with the above, I was wondering if there is anything like that already in Foundation or other 1st party library. Does anyone know of such a thing?
This is a very famous non-protocol because it lacks semantics. For the background on why this is intentionally not a protocol in Swift, see Ole Begemann's writeup Protocols are more than Bags of Syntax. If you have a semantically meaningful protocol that only has this requirement, then there is no problem creating it, but it is quite rare.
The fundamental point of Ole's writeup (which gathers together many other conversations) is that a protocol is more than just "it has this method" (i.e. syntax). It's about what kinds of algorithms it facilitates. "Plusable" wouldn't be a good protocol to cover "things you can apply + to." What + means for Ints is not really the same as what + means for Collections (the latter isn't even commutative). Similarly, "makable by calling init()" tells you nothing about what the resulting object means. Is is "empty?" Some unspecified "default" value? Invalid? The semantics of protocols matter more than the syntax.

isMemberOfClass Terminology - Why is it named the way it is?

I should preface this with saying I come from a Java/Android background which has colored my understanding of the word "member". That said, I'm starting to learn Objective-C and I ran across the isMemberOfClass method and the name confuses me.
I understand that isMemberOfClass returns a Boolean value that indicates whether the receiver is an instance of a given class. However, I don't understand why it is called isMEMBER when it checks if it is an INSTANCE.
Is there something about the language protocol that I don't know that would make sense to name it this? Does member mean something different in Objective-C than it does in Java?
The way I understand the definition of member, it is something a class HAS (method or data), rather than something a class IS (a type).
Can anyone clear this seemingly odd naming convention up for me? Thanks for helping a newbie!
The key note here is that Cocoa (and SmallTalk before it), does not use the word "member" to mean "instance variable" or "function of" or any of the other ways that the word "member" is used in Java or C++. There's a useful paper on SmallTalk from Harry H. Porter III that gives some context:
As mentioned earlier, each object contains zero or more fields. The term "field" is preferable, but other languages use the term "data member" for the same concept. Smalltalk uses the term "instance variable" to mean a field, so we say, "An object contains several instance variables" to mean the same thing as "An object contains several fields" or "An object contains several data members." We will use the terms "field" and "instance variable" interchangeably.
...
In Java or C++, the programmer may add "static data members" and "static member functions" to any class. Smalltalk has a similar ability, although static data members are called "class variables" and static member functions are called "class methods". (Recall that Smalltalk calls normal fields "instance variables" and it calls normal member functions "instance methods".)
In Cocoa, the term "member" is typically used in the context of a collection (see [NSSet member:]). The question being asked by isMemberOfClass: is "is this object a member of the set of all instances of this specific class."
That's not to say isInstanceOfClass: would have been an un-Cocoa-like name. It's just that "member" doesn't have the same meaning here as in some other languages.
The concept of a member as a component of a class (method or data) does not exist in the iOS framework. The framework is also built around verbose and often lengthly method or variable names to promote "added readability" (in quotes because it isn't always necessarily the result).
It easily could be named isInstanceOfClass, but that may have caused some confusion with subclasses. isMemberOfClass just happens to be a simple method name that doesn't collide with any principles of the iOS framework and is quite self explanatory. I don't think the logic extends beyond that.
I believe the term "member" used to denote either an instance variable or a method (sorry, member function) goes back to C++. I personally have never heard it used with Java, but my hearing may not be the best.
Objective-C is pretty much everything C++ is not - and vice versa. Objective-C is historically based on smalltalk and inherits most of that environment's way of doing things. Alan Kay, one of the "inventors" of Smalltalk is quoted as saying "I invented Object-Oriented Programming, and C++ is not what I had in mind", just to illustrate the feelings between the two camps.
So to answer your question: Yes, "member" has a different meaning in Objective-C and C++, and don't be too surprised if you find other words with different meanings as you get deeper into Objective-C.

Classes vs. Functions [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
What is the difference between functional programming and object oriented programming? How should one decide what kind of programming paradigm should be chosen? what are the benefits of one over the other ?
Functions are easy to understand even for someone without any programming experience, but with a fair math background. On the other hand, classes seem to be more difficult to grasp.
Let's say I want to make a class/function that calculates the age of a person given his/her birth year and the current year. Should I create a class for this or a function?
Or is the choice dependent on the scenario?
P.S. I am working on Python, but I guess the question is generic.
Create a function. Functions do specific things, classes are specific things.
Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.
Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.
Like what Amber says in her answer: create a function. In fact when you don't have to make classes if you have something like:
class Person(object):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def compute(self, other):
""" Example of bad class design, don't care about the result """
return self.arg1 + self.arg2 % other
Here you just have a function encapsulate in a class. This just make the code less readable and less efficient. In fact the function compute can be written just like this:
def compute(arg1, arg2, other):
return arg1 + arg2 % other
You should use classes only if you have more than 1 function to it and if keep a internal state (with attributes) has sense. Otherwise, if you want to regroup functions, just create a module in a new .py file.
You might look this video (Youtube, about 30min), which explains my point. Jack Diederich shows why classes are evil in that case and why it's such a bad design, especially in things like API.
It's quite a long video but it's a must see.
i know it is a controversial topic, and likely i get burned now. but here are my thoughts.
For myself i figured that it is best to avoid classes as long as possible. If i need a complex datatype I use simple struct (C/C++), dict (python), JSON (js), or similar, i.e. no constructor, no class methods, no operator overloading, no inheritance, etc. When using class, you can get carried away by OOP itself (What Design pattern, what should be private, bla bla), and loose focus on the essential stuff you wanted to code in the first place.
If your project grows big and messy, then OOP starts to make sense because some sort of helicopter-view system architecture is needed. "function vs class" also depends on the task ahead of you.
function
purpose: process data, manipulate data, create result sets.
when to use: always code a function if you want to do this: “y=f(x)”
struct/dict/json/etc (instead of class)
purpose: store attr./param., maintain attr./param., reuse attr./param., use attr./param. later.
when to use: if you deal with a set of attributes/params (preferably not mutable)
different languages same thing: struct (C/C++), JSON (js), dict (python), etc.
always prefer simple struct/dict/json/etc over complicated classes (keep it simple!)
class (if it is a new data type)
a simple perspective: is a struct (C), dict (python), json (js), etc. with methods attached.
The method should only make sense in combination with the data/param stored in the class.
my advice: never code complex stuff inside class methods (call an external function instead)
warning: do not misuse classes as fake namespace for functions! (this happens very often!)
other use cases: if you want to do a lot of operator overloading then use classes (e.g. your own matrix/vector multiplication class)
ask yourself: is it really a new “data type”? (Yes => class | No => can you avoid using a class)
array/vector/list (to store a lot of data)
purpose: store a lot of homogeneous data of the same data type, e.g. time series
advice#1: just use what your programming language already have. do not reinvent it
advice#2: if you really want your “class mysupercooldatacontainer”, then overload an existing array/vector/list/etc class (e.g. “class mycontainer : public std::vector…”)
enum (enum class)
i just mention it
advice#1: use enum plus switch-case instead of overcomplicated OOP design patterns
advice#2: use finite state machines
Classes (or rather their instances) are for representing things. Classes are used to define the operations supported by a particular class of objects (its instances). If your application needs to keep track of people, then Person is probably a class; the instances of this class represent particular people you are tracking.
Functions are for calculating things. They receive inputs and produce an output and/or have effects.
Classes and functions aren't really alternatives, as they're not for the same things. It doesn't really make sense to consider making a class to "calculate the age of a person given his/her birthday year and the current year". You may or may not have classes to represent any of the concepts of Person, Age, Year, and/or Birthday. But even if Age is a class, it shouldn't be thought of as calculating a person's age; rather the calculation of a person's age results in an instance of the Age class.
If you are modelling people in your application and you have a Person class, it may make sense to make the age calculation be a method of the Person class. A method is basically a function which is defined as part of a class; this is how you "define the operations supported by a particular class of objects" as I mentioned earlier.
So you could create a method on your person class for calculating the age of the person (it would probably retrieve the birthday year from the person object and receive the current year as a parameter). But the calculation is still done by a function (just a function that happens to be a method on a class).
Or you could simply create a stand-alone function that receives arguments (either a person object from which to retrieve a birth year, or simply the birth year itself). As you note, this is much simpler if you don't already have a class where this method naturally belongs! You should never create a class simply to hold an operation; if that's all there is to the class then the operation should just be a stand-alone function.
It depends on the scenario. If you only want to compute the age of a person, then use a function since you want to implement a single specific behaviour.
But if you want to create an object, that contains the date of birth of a person (and possibly other data), allows to modify it, then computing the age could be one of many operations related to the person and it would be sensible to use a class instead.
Classes provide a way to merge together some data and related operations. If you have only one operation on the data then using a function and passing the data as argument you will obtain an equivalent behaviour, with less complex code.
Note that a class of the kind:
class A(object):
def __init__(self, ...):
#initialize
def a_single_method(self, ...):
#do stuff
isn't really a class, it is only a (complicated)function. A legitimate class should always have at least two methods(without counting __init__).
I'm going to break from the herd on this one (Edit 7 years later: I'm not a lone voice on this anymore, there is an entire coding movement to do just this, called 'Functional Programming') and provide an alternate point of view:
Never create classes. Always use functions.
Edit: Research has repeatedly shown that Classes are an outdated method of programming. Nearly every research paper on the topic sides with Functional Programming rather than Object Oriented Programming.
Reliance on classes has a significant tendency to cause coders to create bloated and slow code. Classes getting passed around (since they're objects) take a lot more computational power than calling a function and passing a string or two. Proper naming conventions on functions can do pretty much everything creating a class can do, and with only a fraction of the overhead and better code readability.
That doesn't mean you shouldn't learn to understand classes though. If you're coding with others, people will use them all the time and you'll need to know how to juggle those classes. Writing your code to rely on functions means the code will be smaller, faster, and more readable. I've seen huge sites written using only functions that were snappy and quick, and I've seen tiny sites that had minimal functionality that relied heavily on classes and broke constantly. (When you have classes extending classes that contain classes as part of their classes, you know you've lost all semblance of easy maintainability.)
When it comes down to it, all data you're going to want to pass can easily be handled by the existing datatypes.
Classes were created as a mental crutch and provide no actual extra functionality, and the overly-complicated code they have a tendency to create defeats the point of that crutch in the long run.
Edit: Update 7 years later...
Recently, a new movement in coding has been validating this exact point I've made. It is the movement to replace Object Oriented Programming (OOP) with functional programming, and it's based on a lot of these exact issues with OOP. There are lots of research papers showing the benefits of Functional programming over Object Oriented Programming. In addition to the points I've mentioned, it makes reusing code much easier, makes bugfixing and unit testing fasters and easier. Honestly, with the vast number of benefits, the only reason to go with OOP over Functional is compatibility with legacy code that hasn't been updated yet.
Before answering your question:
If you do not have a Person class, first you must consider whether you want to create a Person class. Do you plan to reuse the concept of a Person very often? If so, you should create a Person class. (You have access to this data in the form of a passed-in variable and you don't care about being messy and sloppy.)
To answer your question:
You have access to their birthyear, so in that case you likely have a Person class with a someperson.birthdate field. In that case, you have to ask yourself, is someperson.age a value that is reusable?
The answer is yes. We often care about age more than the birthdate, so if the birthdate is a field, age should definitely be a derived field. (A case where we would not do this: if we were calculating values like someperson.chanceIsFemale or someperson.positionToDisplayInGrid or other irrelevant values, we would not extend the Person class; you just ask yourself, "Would another program care about the fields I am thinking of extending the class with?" The answer to that question will determine if you extend the original class, or make a function (or your own class like PersonAnalysisData or something).)
Never create classes. At least the OOP kind of classes in Python being discussed.
Consider this simplistic class:
class Person(object):
def __init__(self, id, name, city, account_balance):
self.id = id
self.name = name
self.city = city
self.account_balance = account_balance
def adjust_balance(self, offset):
self.account_balance += offset
if __name__ == "__main__":
p = Person(123, "bob", "boston", 100.0)
p.adjust_balance(50.0)
print("done!: {}".format(p.__dict__))
vs this namedtuple version:
from collections import namedtuple
Person = namedtuple("Person", ["id", "name", "city", "account_balance"])
def adjust_balance(person, offset):
return person._replace(account_balance=person.account_balance + offset)
if __name__ == "__main__":
p = Person(123, "bob", "boston", 100.0)
p = adjust_balance(p, 50.0)
print("done!: {}".format(p))
The namedtuple approach is better because:
namedtuples have more concise syntax and standard usage.
In terms of understanding existing code, namedtuples are basically effortless to understand. Classes are more complex. And classes can get very complex for humans to read.
namedtuples are immutable. Managing mutable state adds unnecessary complexity.
class inheritance adds complexity, and hides complexity.
I can't see a single advantage to using OOP classes. Obviously, if you are used to OOP, or you have to interface with code that requires classes like Django.
BTW, most other languages have some record type feature like namedtuples. Scala, for example, has case classes. This logic applies equally there.

What do we mean by an Object "sending messages" and how do protocols help an object advertise the messages it supports?

What do we mean by an Object "sending messages" and how do protocols help an object to advertise the messages it supports? Does anyone have an example?
It's helpful to think of objects as not merely inanimate objects, but as actors—participants that have knowledge (state), have relationships (to other objects), make decisions, and perform actions (with, to, and upon other objects).
Within this concept, instead of saying “x calls the foo method on y”, which is a very programming-y thing to say, we talk of the objects as talking to each other. We might say “x sends a foo message to y”, or, more specifically, “the text field x tells y that its textFieldDidChange:” or “x asks y what its framistanCalibrationLevel is” or any similar statement that might just as easily be about people as about imaginary objects.
(The reason for the “message” terminology is not entirely conceptual: It's brought over from Smalltalk, one of Objective-C's parent languages. That's the historical reason.)
Protocols are sort of job descriptions. Just as a person may wear the title of Janitor, or Engineer, or Director, or Receptionist, objects that fulfilled those functions might conform to protocols by those names, declaring that those objects respond to messages telling them to do, or asking them about, certain aspects of their job.
In actual Cocoa and Cocoa Touch usage, protocols typically describe a set of functions (again, not in the programming sense) that an object might provide to another object, such as a data source responding to messages by which the view can obtain the data, or a set of notifications that the object might respond to, such as an application delegate's applicationDidFinishLaunching:, applicationWillTerminate:, etc.
Sometimes a protocol can be even more general, like a broader version of a superclass—a real-world analogy being the many different kinds of Salesperson, and a Cocoa example being the many different classes of UI object that respond to validation messages. In some frameworks, you might make an abstract class for this, but protocols let you do the same thing (declare that a bunch of similar but different objects have some properties/abilities in common) without having to write dummy implementations.
Read the Messaging section in Apple's Objective-C Runtime Programming Guide.

Symbols or Case Classes for sending messages to Scala Actors?

In the Scala actor examples I have seen where a parameterless message is sent to an actor (such as this), case classes (or case objects) have been created and then used as messages. Symbols work just as well and look a bit neater and, after reading a book on Erlang, seem more natural. I assume that symbol equality would work for remote actors.
For messages with parameters case classes would be the obvious choice, so perhaps consistency between message types is one issue?
Are there any reasons to go for either approach?
The short answer is compile-time checking.
Even thought symbols can be used as messages and they are even more succinct than case objects (no need to define them), compiler can not detect the misspelled symbols and you will have a hard time figuring out why actors aren't receiving specific messages when they are supposed to.
If case classes and/or objects are used as messages, compiler will tell you if you are trying to send and/or receive non-existent messages before the program is even executed.
I don't think that Symbols are a substitute for using case classes. In fact, I'm not entirely sure what use Symbol is at all, given it lacks the power of symbols in other languages (e.g. Ruby, Smalltalk) - it's just an interned String.
For example, in the standard auction example, it's difficult to see how you would represent the complexity of a bid / offer using symbols alone.
As for case objects, I also believe that these are preferable to symbols. For example, they can be instances of traits etc, and hence supply functionality.