post list

2015년 2월 1일 일요일

Swift(스위프트) 강좌 : 빠르게 시작하기 1

개발 환경 : Xcode6 ,iOS8

Swift 는 애플의 새로운 프로그래밍 언어입니다.

swift 언어를 배우기위해선 Swift reference guide 를 보는 것을 추천하지만 reference guide는 너무 길고 오래걸립니다. 그리고 영어입니다.  이 튜토리얼은 objective-c 같은 객체 지향 언어를 미리 알고있고 익숙하다는 가정하에 swift를 빠르게 배우고 싶은 사람을 위해 만들었습니다.

이 튜토리얼 내용은 Swift reference guide 기준으로 작성되었습니다.

Xcode6 를 시작하고 File\New\File... 에서 Playground  파일을 생성합니다.




전통적으로  새언어를 배울때는  Hello, world 란 구문을 출력해 봐야됩니다.

1
println("Hello,world")
cs
그럼 오른쪽에 결과를 즉시 볼수 있습니다.
swift에서는 입/출력이나 문자열을 다루기 위한 함수를 쓰기 위해 분리된 라이브러리를 불러올 필요가 없습니다.  전역 범위에 해당하는 코드는 프로그램의 진입점으로 사용되기 때문에 main 함수도 필요하지 않습니다. 그리고 끝에 세미콜론을 쓸필요도 없습니다. 쓰고 싶으면 써도 됩니다. 

그리고 상단메뉴에서 View\Assistant Editior\Show Assistant Editor 선택하면 콘솔창을 볼수 있습니다. 

상수(Constants)와 변수(Variables)


상수는 let 키워드를 사용하고  변수선언은 var 을 사용합니다.

1
2
3
4
let Constats  = 10
var Variables = 20
var x = 0.0 , y = 0.0 , z = 2.0 
let string = "Happy ori"
cs

타입명시(Type Annotations)


상수나 변수를 선언할때 바로 초기화를 할경우 알아서 설정이됩니다.

1
var welcomeHappyori : String 
cs

타입변환

1
2
3
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
cs

튜플(Tuples) 

튜플은 여러값들을 하나의 값으로 묶어 줍니다. 여러 값은 각각 동일한 타입일 필요도 없습니다.  이름을 지어줄 수도 있습니다.

1
2
3
let http404Error = (404"Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
let http200Status = (statusCode: 200, description: "OK")
cs

각 튜플의 각 내용들은 분리된 상수나 변수로 분해할수 있고 접근도 가능합니다.

1
2
3
4
5
6
let (statusCode, statusMessage) = http404Error
println("The status code is \(statusCode)")
// prints "The status code is 404"
println("The status message is \(statusMessage)")
// prints "The status message is Not Found"
cs

튜플중 몇개만 필요하다면  "_" 로 무시할 부분을 처리하면 됩니다.

1
2
3
let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// prints "The status code is 404"
cs

0으로 시작하는 index number를 통하여 각각의 element value 에 접근 가능합니다.

1
2
3
4
5
6
7
8
9
println("The status code is \(http404Error.0)")
// prints "The status code is 404"
println("The status message is \(http404Error.1)")
// prints "The status message is Not Found"
println("The status code is \(http200Status.statusCode)")
// prints "The status code is 200"
println("The status message is \(http200Status.description)")
// prints "The status message is OK"
cs

계속....









댓글 없음:

댓글 쓰기