SlideShare a Scribd company logo
SWIFT BASICS 
동의과학대학교 컴퓨터정보계열 
김 종 현 
jhkim@dit.ac.kr 
www.facebook.com/jhkim3217 
2014. 7. 19
Reference 
• Swift Guide, 2014 AppCode.com 
• Swift Tutorial: A Quick Start, Ray 
Wenderlich 
!
background 
• new programming language for iOS, OS X 
Apps 
• Ruby, Python, Go… v.s. Objective-C 
• Fast, Modern, Safe, Interactive 
• Shorter, Cleaner, Easier to read 
• 문법이 웹 개발자에게 친근(특히 Javascript 경험자) 
• user friendly to new programmers
PLAYGROUND
Variable, Constants, 
Type Inference 
• var : 변수 
• let : 상수 
! 
var numberOfRow = 30 
let maxNumberOfRows = 100 
var  = “Have fun!” // emoji character 
! 
const int count = 10; // 항상 명시적으로 형 지정 
double price = 23.55; 
NSString *myMessage = @“Obj-C is not dead yet!”; 
!
let count = 10 
// count is inferred to be type Int 
! 
var price = 23.55 
// price is inferred to be type Double 
! 
var myMessage = “Swift is the future” 
// myMessage is inferred to be type String 
! 
var myMessage : String = “Swift is the future”
No Semicolons 
var myMessage = “No semicolon is needed” 
! 
!
Basic String Manipulation 
• String type is fully Unicode-compliant 
! 
// immutable String 
let dontModifyMe = “You can’t modify this string” 
! 
// mutable String 
var modifyMe = “You can modify this string” 
!! 
• String manipulation 
! 
let firstMessage = “Swift is awesome.” 
let secondMessage = “What do you think?” 
var message = firstMessage + secondMessage
// Objective-C 
NSString *firstMessage = @“Swift is awesome.”; 
NSString *secondMessage = @“What do you think?” 
NSString *message = [NSString 
stringWithFormat:@“%@%@“, firstMessage, 
secondMessage]; 
NSLog(@“%@“, message); 
! 
! 
!
• String Comparison 
! 
var string1 = “Hello” 
var string2 = “Hello” 
if string1 == string2 { 
println(“Both are the same”) 
} else { 
println(”Both are different”) 
} 
! 
결과 값은? 
! 
// Obj-C isEqualToString: method 
!
Array 
! 
// Objective-C, store any type of objects 
NSArray *recipes = @[@“짜장면”, @“짬뽕”, @“탕수육”, 
@“군만두”, @“라면”]; 
! 
// Swift, store items of the same type 
var recipes = ["짜장면", "짬뽕", "탕수육", "군만두", 
"라면", “우동”] 
! 
var recipes : String[] = ["짜장면", "짬뽕", “탕수육”, 
"군만두", "라면"] 
! 
// recipes.count will return 5 
var numberOfItems = recipes.count 
!
// add items 
recipes += “깐풍기” 
! 
// add multiple items 
recipes += [“깐풍기”, “라조기”, “김밥 “] 
! 
// access or change a item in an array 
var recipeItem = recipes[0] 
recipes[1] = “떡뽁기” 
! 
// change a range of values 
recipes[1…3] = [“우동”, “오향장육”, “팔보채”] 
! 
println(recipes) 
! 
!
Dictionary 
// Objective-C 
NSDictionary *companies = @{@“APPL” : @”Apple”, 
@“GOOG” : @“Google”, 
@“FB” : @“Facebook”}; 
! 
// Swift 
var companies = [“APPL” : “Apple”, 
“GOOG” : “Google”, 
“FB” : “Facebook”]; 
! 
var companies: Dictionary<String, String> = 
[“APPL” : “Apple”, 
“GOOG” : “Google”, 
“FB” : “Facebook”]; 
!
// Iteration 
for (stockCode, name) in companies { 
println(“(stockCode) = (name)” 
} 
! 
for stockCode in companies.keys { 
println(“Stock code = (stockCode)”) 
} 
! 
for name in companies.values { 
println(“Companies name = (name)”) 
} 
! 
// add a new key-value pair to Dictionary 
companies[“TWTR”] = “Twitter”
Swift Basics
Classes 
// define a class 
class Recipe { 
var name: String = “” 
var duration: Int = 10 
var ingredients: String[] = [“egg”] 
} 
! 
// optional : ? 
class Recipe { 
var name:String? // assign default value of nil 
var duration: Int = 10 
var ingredients: String[]? 
! 
// create a instance 
var recipeItem = Recipe()
// access or change the property variable 
recipeItem.name = “짜장면” 
recipeItem.duration = 30 
recipeItem.ingredients = [“olive oil”, “salt”, 
“onion”] 
! 
! 
! 
! 
! 
!
Obj-C subclass, protocol 
Integration 
// Objective-C 
@interface SimpleTableViewController : UIViewController 
<UITableViewDelegate, UITableViewDataSource> 
! 
! 
// Swift 
class SimpleTableViewController : UIViewController, 
UITableViewDelegate, UITableViewDataSource 
! 
!
Methods 
• define methods in class, structure or enumeration 
• func keyword 
! 
class TodoManager { 
func printWlecomeMessage() { 
println(“Welcome to My ToDo List”) 
} 
} 
! 
// Swift method call 
toDoManager.printWelcomeMessage() 
! 
// Objective-C 
[toDoManager printWelcomeMessage];
// method arguments, return value 
class ToDoManager { 
func printWelcomeMessage(name:String) -> Int { 
println(“Welcome to (name)’s toDo List”) 
! 
return 10 
} 
} 
! 
var toDoManager = TodoManager() 
let numberOfTodoItem = todoManager.printWelcomeMessage(“Superman) 
println(numberOfTodoItem) 
! 
! 
!
Control Flow 
• for loops 
! 
// .. 
for i in 0..5 { 
println(“index = (i)”) 
} 
! 
for var i=0; i<5; i++ { 
printf(“index = (i)”) 
}
// … 
for i in 0…5 { 
println(“index = (i)”) 
} 
! 
for var i=0; i<=5; i++ { 
printf(“index = (i)”) 
} 
!
• if-else 
! 
var bookPrice = 1000 
if bookPrice >= 999 { 
println(“Hey, the book is expensive”) 
} else { 
println(“Okey, I can buy it”) 
} 
! 
!
• switch 
! 
// break 문이 없음 
swicth recipeName { 
case “짜장면”: 
println(“나의 주식!”) 
case “떡뽁기”: 
println(“나의 간사!”) 
case “김밥”: 
println(“제일 좋아하는 것!”) 
default: 
println(“모두 좋아해!”) 
} 
!
// range matching(.., …) 
var speed = 50 
switch speed { 
case 0: 
println(“stop”) 
case 0…40: 
println(“slow”) 
case 41…70: 
println(“normal”) 
case 71..101 
println(“fast”) 
default: 
println(“not classified yet!”) 
}
Tuples 
• multiple values as a single compound value 
• any value of any type in the tuple 
! 
! 
// create tuple 
let company = (“AAPL”, “Apple”, 93.5) 
! 
// decomposing 
let (stockCode, companyName, stockPrice) = 
company 
println(“stock code = (stockCode)”) 
println(“company name = (companyName)”) 
println(“stock price = (stockPrice)”) 
!
// dot notation 
let product = (id:”AP234”, 
name:”iPhone6”, 
price:599) 
! 
println(“id = (product.id)”) 
println(“name = (product.name)”) 
println(“price = USD(product.price)”) 
! 
! 
! 
! 
! 
!
// return multiple values in a method 
class Store { 
func getProduct(number: Int)->(id: String, name: 
String, price: Int) 
{ 
var id = “IP435”, name = “iMac”, price = 1399 
switch number 
{ 
case 1: 
id = “AP234” 
name = “iPhone 6” 
price = 599 
case 2: 
id = “PE645” 
name = “iPad Air” 
price = 499 
default: 
break 
} 
return(id, name, price) 
} 
} 
! 
//call a method 
let store = Store() 
let product = store.getProduct(2) 
println(“id = (product.id)”) 
println(“name = (product.name)”) 
println(“price = USD(product.price)”)
Enjoy Swift!

More Related Content

PPTX
CoffeeScript - An Introduction
PDF
CoffeeScript
PDF
Happy Programming with CoffeeScript
PDF
Modular JavaScript
PPT
Introduction to Ruby, Rails, and Ruby on Rails
PDF
Es.next
PDF
Coffeescript: No really, it's just Javascript
PPTX
Capstone 발표 pt
CoffeeScript - An Introduction
CoffeeScript
Happy Programming with CoffeeScript
Modular JavaScript
Introduction to Ruby, Rails, and Ruby on Rails
Es.next
Coffeescript: No really, it's just Javascript
Capstone 발표 pt

Similar to Swift Basics (20)

PDF
Swift 3 Programming for iOS : subscript init
PDF
Introduction to Swift programming language.
PDF
Hello Swift Final 5/5 - Structures and Classes
PDF
What's New in Swift 4
PDF
Hello Swift 1/5 - Basic1
PDF
Swift Programming Language
PDF
Swift - the future of iOS app development
PDF
Swift 3 Programming for iOS : Protocol
PDF
Programming Language Swift Overview
PDF
To Swift 2...and Beyond!
PDF
Swift Programming
PDF
Swift Introduction
PPT
iPhone Lecture #1
PPTX
Thinking in swift ppt
PDF
Swift - Krzysztof Skarupa
PDF
Let's golang
PPTX
Introduction to Swift (tutorial)
PDF
Introduction to Swift
PDF
Swift 3 Programming for iOS : extension
PDF
Letswift19-clean-architecture
Swift 3 Programming for iOS : subscript init
Introduction to Swift programming language.
Hello Swift Final 5/5 - Structures and Classes
What's New in Swift 4
Hello Swift 1/5 - Basic1
Swift Programming Language
Swift - the future of iOS app development
Swift 3 Programming for iOS : Protocol
Programming Language Swift Overview
To Swift 2...and Beyond!
Swift Programming
Swift Introduction
iPhone Lecture #1
Thinking in swift ppt
Swift - Krzysztof Skarupa
Let's golang
Introduction to Swift (tutorial)
Introduction to Swift
Swift 3 Programming for iOS : extension
Letswift19-clean-architecture
Ad

More from Jong-Hyun Kim (20)

PPTX
파이썬 AI 드론 프로그래밍
PPTX
Google Teachable machine을 이용한 AI 서비스 만들기
PDF
모두의 AI 교육 : 산 ⦁ 학 ⦁ 관 협력으로 모색해 보는 부산 AI 교육
PPTX
고등직업교육에서의 AI 교육 사례 및 방향
PPTX
Edge AI 및 학생 프로젝트 소개
PPTX
초보 유투버의 IT과목 실시간 온.오프라인 융합 강의 사례
PPTX
Busan Citizen Censor : 부산 시민 참여 스마트시티 오픈데이터 플랫폼
PPTX
IoT Hands-On-Lab, KINGS, 2019
PPTX
부산 전기차(EV) 충전소 네비게이션 모바일 앱 개발
PPTX
micro:bit 프로그래밍 기초
PPTX
프로브 차량(Porbe Vehicle)을 이용한 IoT 기반 실시간 환경 모니터링 시스템
PPTX
딥러닝을 이용한 컬러 테라피 메디컬 IoT 스마트 미러
PPTX
모션 인식을 이용한 스마트 안전 헬맷 개발 및 자전거 사고 빅데이터 분석
PPTX
딥러닝을 이용한 지능형 IoT 스마트 홈 미러
PPTX
클라우드 기반 지능형 IoT 공기청정기
PPTX
스마트 공기 톡톡
PPTX
데이터를 통한 지역 시민과의 소통 : 데이터의 공개와 활용
PDF
모두를 위한 소프트웨어 교육 : 초등학교의 프로젝트 기반 창의융합 SW 교육 사례
PPTX
동의대학교 산업융합시스템학부 특강
PDF
부산 알로이시오 초등학교 창의융합 SW 교육 사례
파이썬 AI 드론 프로그래밍
Google Teachable machine을 이용한 AI 서비스 만들기
모두의 AI 교육 : 산 ⦁ 학 ⦁ 관 협력으로 모색해 보는 부산 AI 교육
고등직업교육에서의 AI 교육 사례 및 방향
Edge AI 및 학생 프로젝트 소개
초보 유투버의 IT과목 실시간 온.오프라인 융합 강의 사례
Busan Citizen Censor : 부산 시민 참여 스마트시티 오픈데이터 플랫폼
IoT Hands-On-Lab, KINGS, 2019
부산 전기차(EV) 충전소 네비게이션 모바일 앱 개발
micro:bit 프로그래밍 기초
프로브 차량(Porbe Vehicle)을 이용한 IoT 기반 실시간 환경 모니터링 시스템
딥러닝을 이용한 컬러 테라피 메디컬 IoT 스마트 미러
모션 인식을 이용한 스마트 안전 헬맷 개발 및 자전거 사고 빅데이터 분석
딥러닝을 이용한 지능형 IoT 스마트 홈 미러
클라우드 기반 지능형 IoT 공기청정기
스마트 공기 톡톡
데이터를 통한 지역 시민과의 소통 : 데이터의 공개와 활용
모두를 위한 소프트웨어 교육 : 초등학교의 프로젝트 기반 창의융합 SW 교육 사례
동의대학교 산업융합시스템학부 특강
부산 알로이시오 초등학교 창의융합 SW 교육 사례
Ad

Recently uploaded (20)

PPTX
GDM (1) (1).pptx small presentation for students
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Pre independence Education in Inndia.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Lesson notes of climatology university.
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Pharma ospi slides which help in ospi learning
PPTX
Institutional Correction lecture only . . .
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
GDM (1) (1).pptx small presentation for students
VCE English Exam - Section C Student Revision Booklet
Pre independence Education in Inndia.pdf
Sports Quiz easy sports quiz sports quiz
Lesson notes of climatology university.
Pharmacology of Heart Failure /Pharmacotherapy of CHF
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Microbial diseases, their pathogenesis and prophylaxis
Pharma ospi slides which help in ospi learning
Institutional Correction lecture only . . .
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
O5-L3 Freight Transport Ops (International) V1.pdf
Insiders guide to clinical Medicine.pdf
Final Presentation General Medicine 03-08-2024.pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx

Swift Basics

  • 1. SWIFT BASICS 동의과학대학교 컴퓨터정보계열 김 종 현 [email protected] www.facebook.com/jhkim3217 2014. 7. 19
  • 2. Reference • Swift Guide, 2014 AppCode.com • Swift Tutorial: A Quick Start, Ray Wenderlich !
  • 3. background • new programming language for iOS, OS X Apps • Ruby, Python, Go… v.s. Objective-C • Fast, Modern, Safe, Interactive • Shorter, Cleaner, Easier to read • 문법이 웹 개발자에게 친근(특히 Javascript 경험자) • user friendly to new programmers
  • 5. Variable, Constants, Type Inference • var : 변수 • let : 상수 ! var numberOfRow = 30 let maxNumberOfRows = 100 var  = “Have fun!” // emoji character ! const int count = 10; // 항상 명시적으로 형 지정 double price = 23.55; NSString *myMessage = @“Obj-C is not dead yet!”; !
  • 6. let count = 10 // count is inferred to be type Int ! var price = 23.55 // price is inferred to be type Double ! var myMessage = “Swift is the future” // myMessage is inferred to be type String ! var myMessage : String = “Swift is the future”
  • 7. No Semicolons var myMessage = “No semicolon is needed” ! !
  • 8. Basic String Manipulation • String type is fully Unicode-compliant ! // immutable String let dontModifyMe = “You can’t modify this string” ! // mutable String var modifyMe = “You can modify this string” !! • String manipulation ! let firstMessage = “Swift is awesome.” let secondMessage = “What do you think?” var message = firstMessage + secondMessage
  • 9. // Objective-C NSString *firstMessage = @“Swift is awesome.”; NSString *secondMessage = @“What do you think?” NSString *message = [NSString stringWithFormat:@“%@%@“, firstMessage, secondMessage]; NSLog(@“%@“, message); ! ! !
  • 10. • String Comparison ! var string1 = “Hello” var string2 = “Hello” if string1 == string2 { println(“Both are the same”) } else { println(”Both are different”) } ! 결과 값은? ! // Obj-C isEqualToString: method !
  • 11. Array ! // Objective-C, store any type of objects NSArray *recipes = @[@“짜장면”, @“짬뽕”, @“탕수육”, @“군만두”, @“라면”]; ! // Swift, store items of the same type var recipes = ["짜장면", "짬뽕", "탕수육", "군만두", "라면", “우동”] ! var recipes : String[] = ["짜장면", "짬뽕", “탕수육”, "군만두", "라면"] ! // recipes.count will return 5 var numberOfItems = recipes.count !
  • 12. // add items recipes += “깐풍기” ! // add multiple items recipes += [“깐풍기”, “라조기”, “김밥 “] ! // access or change a item in an array var recipeItem = recipes[0] recipes[1] = “떡뽁기” ! // change a range of values recipes[1…3] = [“우동”, “오향장육”, “팔보채”] ! println(recipes) ! !
  • 13. Dictionary // Objective-C NSDictionary *companies = @{@“APPL” : @”Apple”, @“GOOG” : @“Google”, @“FB” : @“Facebook”}; ! // Swift var companies = [“APPL” : “Apple”, “GOOG” : “Google”, “FB” : “Facebook”]; ! var companies: Dictionary<String, String> = [“APPL” : “Apple”, “GOOG” : “Google”, “FB” : “Facebook”]; !
  • 14. // Iteration for (stockCode, name) in companies { println(“(stockCode) = (name)” } ! for stockCode in companies.keys { println(“Stock code = (stockCode)”) } ! for name in companies.values { println(“Companies name = (name)”) } ! // add a new key-value pair to Dictionary companies[“TWTR”] = “Twitter”
  • 16. Classes // define a class class Recipe { var name: String = “” var duration: Int = 10 var ingredients: String[] = [“egg”] } ! // optional : ? class Recipe { var name:String? // assign default value of nil var duration: Int = 10 var ingredients: String[]? ! // create a instance var recipeItem = Recipe()
  • 17. // access or change the property variable recipeItem.name = “짜장면” recipeItem.duration = 30 recipeItem.ingredients = [“olive oil”, “salt”, “onion”] ! ! ! ! ! !
  • 18. Obj-C subclass, protocol Integration // Objective-C @interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> ! ! // Swift class SimpleTableViewController : UIViewController, UITableViewDelegate, UITableViewDataSource ! !
  • 19. Methods • define methods in class, structure or enumeration • func keyword ! class TodoManager { func printWlecomeMessage() { println(“Welcome to My ToDo List”) } } ! // Swift method call toDoManager.printWelcomeMessage() ! // Objective-C [toDoManager printWelcomeMessage];
  • 20. // method arguments, return value class ToDoManager { func printWelcomeMessage(name:String) -> Int { println(“Welcome to (name)’s toDo List”) ! return 10 } } ! var toDoManager = TodoManager() let numberOfTodoItem = todoManager.printWelcomeMessage(“Superman) println(numberOfTodoItem) ! ! !
  • 21. Control Flow • for loops ! // .. for i in 0..5 { println(“index = (i)”) } ! for var i=0; i<5; i++ { printf(“index = (i)”) }
  • 22. // … for i in 0…5 { println(“index = (i)”) } ! for var i=0; i<=5; i++ { printf(“index = (i)”) } !
  • 23. • if-else ! var bookPrice = 1000 if bookPrice >= 999 { println(“Hey, the book is expensive”) } else { println(“Okey, I can buy it”) } ! !
  • 24. • switch ! // break 문이 없음 swicth recipeName { case “짜장면”: println(“나의 주식!”) case “떡뽁기”: println(“나의 간사!”) case “김밥”: println(“제일 좋아하는 것!”) default: println(“모두 좋아해!”) } !
  • 25. // range matching(.., …) var speed = 50 switch speed { case 0: println(“stop”) case 0…40: println(“slow”) case 41…70: println(“normal”) case 71..101 println(“fast”) default: println(“not classified yet!”) }
  • 26. Tuples • multiple values as a single compound value • any value of any type in the tuple ! ! // create tuple let company = (“AAPL”, “Apple”, 93.5) ! // decomposing let (stockCode, companyName, stockPrice) = company println(“stock code = (stockCode)”) println(“company name = (companyName)”) println(“stock price = (stockPrice)”) !
  • 27. // dot notation let product = (id:”AP234”, name:”iPhone6”, price:599) ! println(“id = (product.id)”) println(“name = (product.name)”) println(“price = USD(product.price)”) ! ! ! ! ! !
  • 28. // return multiple values in a method class Store { func getProduct(number: Int)->(id: String, name: String, price: Int) { var id = “IP435”, name = “iMac”, price = 1399 switch number { case 1: id = “AP234” name = “iPhone 6” price = 599 case 2: id = “PE645” name = “iPad Air” price = 499 default: break } return(id, name, price) } } ! //call a method let store = Store() let product = store.getProduct(2) println(“id = (product.id)”) println(“name = (product.name)”) println(“price = USD(product.price)”)