[Swift] Type component ~ Method ~

What is a method

The method is a function associated with the type.

It is used to realize the functionality (behavior) of an instance of a type.

Definition method

The way to define a method is to use the func keyword inside the type definition. ** Method names, arguments, and return values ​​have the same syntax as functions. ** **


func method name(Argument name:Argument type) ->Return type{
Statement executed when a method is called
}

To call a method, a variable or constant to which an instance of the type is assigned, Add. (Dot), method name and (), and write as variable name.method name (argument).

** If the method requires multiple arguments Describe multiple arguments separated by, (comma). ** **

I wrote an example of a method that requires two arguments.


struct Message {
    func hello(name: String, message: String) {
        print("\(name)Mr.\(message)")
    }
}

let sample = Message()
sample.hello(name: "Tanaka", message: "Hello")
sample.hello(name: "Saito", message: "goodbye")

Execution result
Mr. Tanaka, Hello
Goodbye, Mr. Saito

Targets and classifications to be linked

Like properties, methods also have ** instance methods ** associated with type instances, There is a ** static method ** associated with the type itself.

Instance method

An instance method is a method associated with an instance of a type, as mentioned earlier. When I say a method, I think it often refers to an instance method.

** The method defined by the func keyword is The default is an instance method. ** **

Since the instance method is tied to the instance, Different instances return different results.

I declared the constants sample1 and sample2 and instantiated each with the same type.

At this time, both have the same properties and methods, ** Since it is an instance property in the instance method, the value of the contents is different. ** **


struct Sample {
    var name: String
    var message: String
    
    init(name: String, message: String) {
        self.name = name
        self.message = message
    }
    
    func say() {
        print("\(message) \(name) !")
    }
}

let sample1 = Sample(name: "Tanaka", message: "Hello")
let sample2 = Sample(name: "Watabe", message: "Good bay")

sample1.say()
sample2.say()

Execution result
Hello Tanaka !
Goodbay Watabe !

Static method

I mentioned the static method earlier, ** It is a method associated with the type itself and performs instance-independent processing. ** **

How to define a static method Add ** static keyword ** to the beginning of the method definition to define it.

When calling a static method Must be called in the form type name.method name (argument).

Other processes are not particularly difficult, so explanations are omitted.


struct Proverb {
    static var word = "The early bird gets the worm"
    
    static func changeWord(word: String){
        self.word = word
    }
    
    let plusWord = "Today's saying is"
    var getWord: String {
        return "\(plusWord)、\(Proverb.word)"
    }
}

let proverb = Proverb()

print(proverb.getWord)
print("---")

Proverb.changeWord(word: "Even monkeys fall from trees")
print(proverb.getWord)

Execution result
Today's saying is that getting up early is a virtue of three sentences
---
Today's saying is that monkeys also fall from trees

Overload

Overloading is the preparation of multiple ** methods with the same name ** that take arguments and return values ​​of different types. It is a method to switch the method to be executed according to the type passed to the argument and the type to which the return value is assigned.

** Although the argument type and return type are different, This is a convenient function when defining a method with similar contents processing. ** **

By overloading It is used to make the caller unaware of these differences.

Argument overload

To overload a method with arguments, Define multiple methods with the same name with different argument types.

You can see that the method to be executed is switched from the execution result of the sample code.


struct Sample {
    func test(a: Int) {
        print("Int : \(a)")
    }
    func test(a: String) {
        print("String: \(a)")
    }
}

let sample = Sample()
sample.test(a: 123)
sample.test(a: "abc")

Execution result
Int : 123
String: abc

Overload due to return value

To overload a method with a return value Define multiple methods with the same name with different return types.

If overloaded by return type ** The method to be executed changes depending on the type to which the return value is assigned. ** **

But if the return type cannot be inferred, A compile error will occur because the method to be executed cannot be determined.


struct Sample {
    let intValue = 123
    let stringValue = "abc"
    
    func getValue() -> Int {
        return intValue
    }
    
    func getValue() -> String {
        return stringValue
    }

}

let sample = Sample()
let intValue: Int = sample.getValue()   // 123
let stringValue: String = sample.getValue()   // abc
let value = sample.getValue()   //Compile error

Error details: Ambiguous use of'getValue ()' Japanese translation: Ambiguous use of'getValue ()'

The above is the explanation of the method.

It's almost the same as when defining a function, so I think it's not that difficult, but Overlord was a new knowledge, so I learned by writing an article!

It's hard to use at the moment, I thought it was quite important knowledge, so I want to remember it.

There are other articles about type components, so be sure to check them out!

-[Swift] Type component-Type basics- -[Swift] type component-property first part- -[Swift] type component ~ initializer ~ -[Swift] type component ~ subscript ~ -[Swift] type component ~ extension ~ -[Swift] Type component ~ Type nesting ~

Thank you for watching until the end.

Recommended Posts

[Swift] Type component ~ Method ~
[Swift] Type component ~ Subscript ~
[Swift] Type component ~ Initializer ~
[Swift] Type component ~ Property Part 2 ~
[Swift] Type type ~ Enumeration type ~
[Swift] Type type ~ Structure ~
[Swift] Type components ~ Type nesting ~
[Swift] Type design guidelines
[Swift] Shared enumeration type
[Swift] Type type-Class sequel-
[Swift] Summary about Bool type
[Swift] Type type-Class first part-
Great Swift pointer type commentary
Method
[Swift] Protocol concept and definition method
[Swift] Converts a UInt64 type integer to [UInt8]