이번주에 보고 갈것들
- 함수
- 메소드
1-1. 함수란?
특정 작업하는 수행하는 코드 블록 , 실행시 데이터를 제공해야 하거나 또는 함수를 호출한 코드에 작업한 결과를 반환
매개변수와 (parameter) , 인수는 (argument) 차이가 존재함
The terms parameter and argument may have different meanings in different programming languages.
Sometimes they are used interchangeably, and the context is used to distinguish the meaning.
매개 변수와 인수라고 하는 용어는 프로그래밍 언어마다 다른의미를 가질수 있습니다.
때로는 서로 교환하여 사용할수도 있고, 문맥의 의미를 구분하는데에도 쓰일수 있습니다.
The term parameter(sometimes called formal parameter) is often used to refer to the variable as found in the function definition, while argument (sometimes called actual parameter) refers to the actual input supplied at function call.
매개변수는 (형식 매개변수) 용어는 때때로 함수 정의에서 볼수 있는 변수를 지칭할때 사용됩니다.
인수(실사용 매개변수)는 함수 호출시 제공되는 실제 입력을 의미합니다.
1-2. 전달인자/매개변수 vs 리턴값 (반환값)
1-3. 메소드란? - 클래스,구조체,열거형 내의 함수 (클래스내에 선언시 메소드라고 부름)
Argument label vs Parameter name
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/functions/
1-4. 함수를 선언하는 방법 (Swift 언어 기준이니 오해 금지)
2-1. 단순한 Swift함수 정의 예시
func sayHello()
{ print("Hello") }
sayHello() //호출
2-2. C ++ 언어 > swift 변환 1 ( C , C ++ vs Swift )
int add(int x, int y, int z) { //C, C++
return(x+y+z);
}
add(10,20,30); //60
func add(x: Int, y: Int, z: Int) -> Int //swift
{ return(x+y+z) }
add(x:10, y:20, z:30) //60
두개를 보니 뭔가 많이 다르시죠?
근데 여기서 추가질문, 함수의 자료형을 알려면 어떻게 해야할까요? 힌트는 print(type of)...인데 아시나요?
바로 아래코드처럼 한줄만 추가해주면 됩니다.
func add(x: Int, y: Int, z: Int) -> Int //swift
{ return(x+y+z) }
add(x:10, y:20, z:30) //60
print(type(of:add)) //add의 자료형을 출력하라는 코드입니다.
// 표시타입 (자료형, 자료형...) -> 리턴형
//(Int, Int, Int) -> Int
2-3. 내부 매개 변수 이름과 외부 매개 변수의 이름
2-4. 함수들의 다양한 예시
func add(x: Int, y: Int) -> Int // x:y:
{ return x+y }
print(add(x:10, y:20))
func add(first x: Int, second y: Int) -> Int //first: second:
{ return x+y }
print(add(first:10, second:20))
func add(_ x: Int, _ y: Int) -> Int // 모두 생략, 생략후 미지정시 기본형 x,y가 나옴
{ return x+y }
print(add(10, 20))
func add(_ x: Int, with y: Int) -> Int // (_:with:)
{ return x+y }
print(add(10, with:20))
//print(type(of:add)) 사용하면? 모두 Int형이긴 하나, 함수명은 각각다름
2-5. C ++ 언어 > swift 변환 2
// C , C ++
int ddd(int x)
{ return(x*2); }
void setX(int x)
{ xx=x; }
int getX()
{ return(x); }
int add(int x, int y)
{ return(x+y) }
void setXY(int x, int y)
{ xx=x; yy=y;}
var xx: Int = 0
var yy: Int = 0
func ddd(_ x: Int) -> Int
{ return x * 2 }
func setX(_ x: Int)
{ xx = x }
func getX() -> Int
{ return xx }
func add(_ x: Int, _ y: Int) -> Int
{ return x + y }
func setXY(_ x: Int, _ y: Int)
{ xx = x, yy = y}
2-6. 함수명을 알고 싶을땐? (#function) 사용
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/expressions/
2-7 함수명과 자료형
https://developer.apple.com/documentation/uikit/uitableviewdatasource
UITableViewDataSource | Apple Developer Documentation
The methods that an object adopts to manage data and provide cells for a table view.
developer.apple.com
https://developer.apple.com/documentation/uikit/uitableviewdatasource/1614931-tableview
tableView(_:numberOfRowsInSection:) | Apple Developer Documentation
Tells the data source to return the number of rows in a given section of a table view.
developer.apple.com
↓ 영어를 해석하기 힘드시다면 챗GPT에게 물어보는것도 한가지 방법입니다. ↓
3-1. 디폴트 매개변수 정의하기
3-2. 함수로부터 여러개의 결과 반환
func converter(length: Float) -> (yards: Float, centimeters: Float, meters: Float)
{
let yards = length * 0.0277778
let centimeters = length * 2.54
let meters = length * 0.0254
return (yards, centimeters, meters)
}
var lengthTuple = converter(length:100)
print(lengthTuple) // (yards: 2.77778, centimeters: 254.0, meters: 2.54)
print(lengthTuple.yards) // 2.77778
print(lengthTuple.centimeters) // 254.0
print(lengthTuple.meters) // 2.54
3-3. 2개의 정수를 받아 가감제 리턴
func sss(x : Int, y : Int) -> (sum : Int, sub : Int, div : Double)
{
let sum = x+y
let sub = x-y
let div = Double(x)/Double(y) //같은 자료형만 연산 가능
return (sum, sub, div)
}
var result = sss(x:10,y:3)
print(result.sum)
print(result.sub)
print(result.div)
밑의 코드는 가감승제, 나머지까지 나오게 하는 코드입니다.
import Foundation
func sss(x: Int, y: Int) -> (sum: Int, sub: Int, mul: Int, div: Double, mod: Int) {
let sum = x + y
let sub = x - y
let mul = x * y
let div = Double(x) / Double(y)
let mod = x % y // 나머지 계산
return (sum, sub, mul, div, mod)
}
let result = sss(x: 10, y: 3)
// 소수점 3자리에서 반올림
let roundedDiv = String(format: "%.3f", result.div)
print(result.sum)
print(result.sub)
print(result.mul)
print(roundedDiv)
print(result.mod)
print(type(of:sss))
// (Int, Int) -> (sum: Int, sub: Int, mul: Int, div: Double, mod: Int)
3-4. 가변적 매개변수
func sum(of numbers: Int...) -> Int {
return numbers.reduce(0, +)
}
// 사용 예시
let result1 = sum(of: 1, 2, 3, 4, 5, 6 ) // 21
let result2 = sum(of: 10, 20, 30, 40) // 100
let result3 = sum(0, 0, 0, 0, 0) // 0
print(result1)
print(result2)
print(result3)
3-5. inout 매개변수
//Swift 2
/*var myValue = 10
func doubleValue (inout value: Int) -> Int {
value += value
return(value)
}
doubleValue(value:&myValue)*/
var myValue = 10
func doubleValue (value: inout Int) -> Int {
value += value
return(value)
}
print(myValue) //10
print(doubleValue(value : &myValue)) //20
print(myValue) //20
'iOS' 카테고리의 다른 글
iOS 프로그래밍 기초 (6주) [클래스 , failable , initialize , 상속 , self] (2) | 2024.10.14 |
---|---|
iOS 프로그래밍 기초 (5주) [ first class object , citizen , 클로저] (0) | 2024.10.05 |
iOS 프로그래밍 기초 (3주) [optional,as,nil,연산자,제어문] (1) | 2024.09.20 |
iOS 프로그래밍 기초 (2주) [자료형,변수,상수,tuple] (0) | 2024.09.18 |
iOS 프로그래밍 기초 (1주) (4) | 2024.09.18 |
댓글