var x = 10
if x > 5 {
print("5보다 큽니다")
}
guard문은 표현식이 거짓(false)으로 판단될 경우에 수행될 else 절을 반드시 포함해야 함
guard <불리언 표현식> else {
// 표현식이 거짓일 경우에 실행될 코드
<코드 블록을 빠져 나갈 구문>
}
// 표현식이 참일 경우에 실행되는 코드는 이곳에 위치
guard문은 기본적으로 특정 조건에 맞지 않을 경우에 현재의 함수나 반복문에서 빠져 나갈 수 있도록 하는 ‘조기 출구(early exit)’ 전략을 제공
// if let
func printName(firstName:String, lastName:String?){
if let lName = lastName { // lastName이 nil이 아니면
print(lName,firstName)
}
else {
print("성이 없네요!")
}
--------------------------------------------------------
// guard let
func printName(firstName:String, lastName:String?){
guard let lName = lastName else { // lastName이 nil이면
print("성이 없네요!")
return // early exit
}
print(lName,firstName) // guard let의 특징 : lName을 guard let 블럭 밖에서도 쓸수있다
}
printName(firstName: "길동", lastName:"홍")
printName(firstName: "길동", lastName:nil)
func multiplyByTen(value: Int?) {
guard let number = value, number < 10 else {//조건식(값이 있고 10보다 작은)이 거짓일 때 실행
print("수가 없거나 10보다 크다.") //거짓 : 값이 없거나 10보다 크면
return
}
print(number*10) //조건식이 참일 때 실행, 주의 : number를 여기서도 사용 가능
}
multiplyByTen(value: 3) //30
multiplyByTen(value: nil)
multiplyByTen(value: 20)
// 실행결과
30
수가 없거나 10보다 크다.
수가 없거나 10보다 크다.
switch 표현식
{
case match1:
구문
case match2:
구문
case match3, match4:
구문
default:
구문
}
var value = 0
switch value
{
case 0:
print("영")
case 1:
print("일")
case 2:
print("이")
case 3:
print("삼")
default:
print("4이상")
}
// 실행결과
영
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
print("The letter A")
default:
print("Not the letter A")
}
//error: 'case' label in a 'switch' should have at least one executable statement
var value = 3
var days : Int = 0
switch(value)
{
case 1,3,5,7,8,10,12:
print("31 일입니다")
case 4,6,9,11:
print("30 일입니다")
case 2:
print("28 or 29 일입니다")
default:
print("월을 잘못 입력하셨습니다")
}
// 31 일입니다
let weight = 90.0
let height = 180.0
let bmi = weight / (height*height*0.0001) // kg/m*m
var body = ""
switch bmi {
case 40... :
body = "3단계 비만"
case 30..<40:
body = "2단계 비만"
case 25..<30:
body = "1단계 비만"
case 18.5..<25:
body = "저체중"
default:
body = "정상"
}
print("BMI:\(bmi), 판정:\(body)")
var temperature = 60
switch (temperature)
{
case 0...49 where temperature % 2 == 0:
print("Cold and even")
case 50...79 where temperature % 2 == 0:
print("Warm and even")
case 80...110 where temperature % 2 == 0:
print("Hot and even")
default:
print("Temperature out of range or odd")
}
// Warm and even
var numbers: [Int] = [1, 2, 3, 4, 5]
for num in numbers where num > 1 {
print(num)
}
//
2
3
4
5
var value = 4
switch (value)
{
case 4:
print("4")
fallthrough
case 3:
print("3")
fallthrough
case 2:
print("2")
fallthrough
default:
print("1")
}
//
4
3
2
1
#include <stdio.h>
void Fun( int Param ) // parameter(매개변수, 인자), 형식 매개변수(formal parameter)
{
printf("%d",Param);
}
int main()
{
Fun( 10 ); // 10은 argument(인수), 실 매개변수(actual parameter)
return 0;
}
func <함수명> (<매개변수 이름>: <매개변수 타입>, <매개변수 이름>: <매개변수 타입>,... ) -> <반환값 타입> {
// 함수 코드
}
매개변수를 받지 않으며 결과를 반환하지도 않고 오직 메시지만 출력
func sayHello() { //리턴값 없으면( -> Void ) 지정하지 않아도 됨
print("Hello")
}
sayHello()
func sayHello() { //->Void
print("Hello")
}
sayHello() //호출
int add(int x, int y) { //C, C++
return(x+y);
}
add(10,20);
---------변경---------------
func add(x:Int, y:Int) -> Int {
return (x+y)
}
print(add(x:10, y:20))
func add(x:Int, y:Int) -> Int {
return (x+y)
}
print(type(of:add))
print(add(x:10, y:20))
let a = add(x:1, y:2)
print(a)
func sayHello() { // -> Void
print("Hello")
}
print(type(of:sayHello))
// (Int, Int) -> Int
// 30
// 3
// () -> ()
func add(first x:Int, second y:Int) -> Int {
//외부 내부:자료형,외부 내부:자료형 -> 리턴형
return (x+y) // 함수 정의할 때는 내부 매개변수명을 사용
}
print(add(first:10,second:20)) // 함수 호출할 때는 외부 매개변수명을 사용
// 30
func add(x: Int, y: Int) -> Int {
return(x+y)
}
add(x:10, y:20)
func add(first x:Int, second y:Int) -> Int {
return (x+y)
} // 함수명 : add(first:second:)
func add( x:Int, y:Int) -> Int {
return (x+y)
} // 함수명 : add(x:y:)
func add(_ x:Int,_ y:Int) -> Int { // _ 는 외부매개변수명 생략 의미
return (x+y)
} // 함수명 : add(_:_:)
func add(_ x:Int,with y:Int) -> Int {
return (x+y)
} // 함수명 : add(_:with:)
print(add(3, 5))
print(add(x:3, y:5))
print(add(3, 5))
print(add(3, with:5))
func add(first x: Int, second y: Int) -> Int {
print(#function) //add(first:second:)
return(x+y)
}
let a = add(first:10, second:20)
// 실행결과 : add(first:second:)
함수명
tableView( _: numberOfRowsInSection:)
tableView( _: cellForRowAt:)
자료형
(UITableView,Int) -> Int
(UITableView, IndexPath) -> UUTableViewCell
func sayHello(count: Int, name: String = "안녕?") -> String { return ("\(name), 너의 번호는 \(count)") }
var message = sayHello(count:10, name: "철수") //철수, 너의 번호는 10
var message = sayHello(count:100) print(message) //안녕?, 너의 번호는 100
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:10)
print(lengthTuple) //과제
print(lengthTuple.yards) //과제
print(lengthTuple.centimeters) //과제
print(lengthTuple.meters) //과제
// (yards: 0.277778, centimeters: 25.4, meters: 0.254)
// 0.277778
// 25.4
// 0.254
func sss(x : Int, y : Int) -> (sum : Int, sub : Int, mul : Int, div : Double)
{
let sum = x+y
let sub = x-y
let mul = x*y
let div = Double(x)/Double(y) //같은 자료형만 연산 가능
return (sum, sub, mul, div)
}
var result = sss(x:10,y:3)
print(result.sum)
print(result.sub)
print(result.mul)
print(result.div)
func displayStrings(strings: String...)
{
for string in strings {
print(string)
}
}
displayStrings(strings: "일", "이", "삼", "사")
displayStrings(strings: "one", "two")
func add(numbers:Int...)
{
var sum:Int = 0
for num in numbers{
sum += num
}
print(sum)
}
add(numbers:1,2,3)
var myValue = 10
func doubleValue (value: inout Int) -> Int {
value += value
return(value)
}
print(myValue)
print(doubleValue(value : &myValue)) //출력 값? 레포트
print(myValue)
//
10
20
20
출처:iOS프로그래밍기초 (22-2학기)한성현교수님 강의 내용 변형 및 요약 5주차