Get a rough idea of the differences between protocols, classes and structs!

This time, I learned about the differences in protocols, classes, and structures, so I will output them.

What is a protocol?

A literal translation of a protocol means something like a "treaty," "protocol," or "covenant." In the Swift language, it means "every promise between the developer and the Swift language".

First, let's see how to write a declaration.

qiita.rbvar


protocol <Protocol name> {
}

Basically, you declare it like this. The only difference from class is that the keyword "class" has become "protocol". Let's dig deeper.

Method in protocol

From here, the clear difference between the protocol and the class is that the *** protocol does not write the contents of the method when writing the method. *** *** The writing method is as follows.

qiita.rbvar


protocol <Protocol name> {
     func<Method name>()
}

*** At first glance, the format is similar to a class, but there is no {} after the method name ()! *** ***

How to use the protocol

The fact that the protocol does not write the contents of the method means that it does not make sense to just declare it.

Let's go deep into how to use it. Basically, the protocol is used as a set with "class".

qiita.rbvar


class <name of the class> <Protocol name> {
 }

Write the protocol name after the ":" in the class declaration. This way of writing a protocol in a class is called *** ratification ***. If you ratify a protocol, you must implement the methods defined in that protocol. If it is not implemented, an error will occur.

Next, let's look at it concretely.

qiita.rbvar


protocol MorningProtocol {
     func morningAction()
}

qiita.rbvar


class Date:MorningProtocol {
  func morningAction(){
  print("Eat breakfast")
  print("Brush your teeth")
}

In the above, what to do after waking up in the morning is output to the debug area. This is the most basic use of the protocol

Protocol as a type

The protocol has a function as a type. When declaring a variable name, if you specify the protocol name by adding ":" after the variable name, the variable becomes a box dedicated to the class that has ratified the protocol.

qiita.rbvar


var <Variable name>:<Protocol name> = <name of the class> ()

What is a class?

The class is interpreted as a template. Classes are often used as an example to imagine the mold used to make Taiyaki.

The class declaration is as follows.

qiita.rbvar


class <name of the class> ()

Method declaration in class

The declaration method is as follows

qiita.rbvar


class <name of the class> {
  func<Method name>(){}

}

Next, let's declare concretely

qiita.rbvar


class Hamburger {
   var nakami = "Patty"

 func sayNakami () {
 print("The contents are"+nakami+"is") //The contents areパティis
}

Now let's actually create a class using the class created above.

qiita.rbvar


var hamburger = Hamburger()
hamburger.nakami = "Patty and cheese"
hamburger.sayNakami() //The contents are patties and cheese.

In the above example, an instance is created based on the class, and the instance is operated and processed. Cheese is added to the value of the nakami property to change the string.

What is a structure?

In a nutshell, the difference between classes and protocols A class that cannot be inherited!

The basic writing method is as follows.

qiita.rbvar


struct structure name{
var property name: property type=formula
let property name: property type=formula
}

Let's look at a concrete example next

qiita.rbvar


struct SomeStruct {
   var num1 = 246
   let num2 = 135
}

let someStruct = SomeStruct()
let a = someStruct.num1 //246
let b = someStruct.num2 //135

Deepen the difference between structs and classes

In the above, I wrote that the difference between a class and a structure is whether it can be inherited or not, but let's look at a concrete example here.

qiita.rbvar


//Structure(Value type)
struct ColorStruct {
    var color:String
}

//class(Reference type)
class ColorClass {
    var color:String

    init(color:String){
        self.color = color
    }
}

var colorStruct1 = ColorStruct(color: "Blue")
var colorStruct2 = colorStruct1
colorStruct2.color = "black"
println("colorStruct1:\(colorStruct1.color)、colorStruct2:\(colorStruct2.color)")

For output result structure, colorStruct2.Changing color does not change colorStruct1
"colorStruct1:Blue, colorStruct1:black"


var colorClass1 = ColorClass(color: "Blue")
var colorClass2 = colorClass1
cardClass2.color = "black"
println("colorClass1:\(colorClass1.color)、colorClass2:\(colorClass2.color)")


For the output result structure, colorClass2.If you change color, colorClass1 will also change
"colorClass1:black, colorClass2:black"

As mentioned above, we can see that the structures are not inherited and have independent concepts one by one.

Summary

When I was learning this time, the difference between the protocol, the class, and the structure was ... "What? How was it?", So I summarized it roughly!

Recommended Posts

Get a rough idea of the differences between protocols, classes and structs!
Understand in 3 minutes! A very rough explanation of the difference between session and cookie
Differences between preface and postfix of operators
About the idea of anonymous classes in Java
Rails logger Get a rough idea in 1 minute
Summarize the differences between C # and Java writing
I want to recursively get the superclass and interface of a certain class
Is there a performance difference between Oracle JDK and OpenJDK at the end of 2017?
What is the difference between a class and a struct? ?? ??
About the difference between classes and instances in Ruby
Verification of the relationship between Docker images and containers
Fargate to get a rough idea in relation to EC2
The idea of quicksort
The idea of jQuery
I want to get a list of the contents of a zip file and its uncompressed size
[Ruby] How to get the value by specifying the key. Differences between hashes, symbols and fetch
[Java] Throw a request and display the screen ② (GET / POST)
[Java] Throw a request and display the screen (GET / POST)
The nth and n + 1st characters of a Ruby string
I tried JAX-RS and made a note of the procedure
[Ruby] Creating code using the concept of classes and instances
[Ruby] About the difference between 2 dots and 3 dots of range object.
Think about the differences between functions and methods (in Java)
[jsoup] How to get the full amount of a document
The difference between programming with Ruby classes and programming without it
Differences between IndexOutOfBoundsException and ArrayIndexOutOfBoundsException
Try to imitate the idea of a two-dimensional array with a one-dimensional array
[Java] Various summaries attached to the heads of classes and members
[Rails] How to get the URL of the transition source and redirect
[Java] Get the dates of the past Monday and Sunday in order
Get a proxy instance of the component itself in Spring Boot
[Ruby] Relationship between parent class and child class. The relationship between a class and an instance.
[Ruby] Difference between symbol variables and character string variables. About the difference between [: a] and ['a'].
Java, JS (jQuery) and Ajax. Get a specific value of JSON.
Method to add the number of years and get the end of the month
What is the difference between a web server and an application server?
Get the public URL of a private Flickr file in Java
Get the acceleration and bearing of the world coordinate system on Android