2014년 12월 22일 월요일

애플의 새로운 개발언어 Swift - 배열#7

// Playground - noun: a place where people can play

import UIKit

var productNames = ["iPhone", "iPad", "Mac Pro", "iPad", "Macbook Pro"]
//범위 연산자로 1,2,3 출력
productNames[1...3] = ["iWatch", "Macbook air"]
for item in productNames
{
    println(item)
}
//범위 연산자로 0, 1 출력(2 제외)
productNames[0..<2] = ["Apple TV"]
for item in productNames
{
    println(item)
}

//삭제할 경우 removeAtIndex 사용한다.
var productNames2 = ["iPhone", "iPad", "Mac Pro", "iPad", "Macbook Pro"]
let firstProduct = productNames2.removeAtIndex(0)
println(firstProduct)

let lastProduct = productNames2.removeLast()
println(lastProduct)

//배열을 순회하는 것은 for-in절을 사용
for name in productNames2 {
    println(name)
}

//Swift enumerate전역 함수는 순회의 단계마다 인덱스와 값으로 구성된 튜플을
//리턴한다
for (index, name) in enumerate(productNames2) {
    println("# \(index+1) : \(name)")
}

//딕셔너리도 배열과 마찬가지로 템플릿 형태와 문법과 축약된 문법(슈가 문법) 모두 지원한다.
var countryCodes:Dictionary<String, String> = ["KR":"Korea, Republic of", "US":"United States", "FR":"France"]
println("Dictionary contains \(countryCodes.count) items")

if countryCodes.isEmpty {
    println("Empty Dictionary")
}

//특정 키의 값을 가져오기 
var countryCodes2:Dictionary<String, String> = ["KR":"Korea, Republic of", "US":"United States", "FR":"France"]
if let countryName = countryCodes2["IT"] {
    print("IT => \(countryName)")
}
else {
    println("Key \"IT\" not exist")
}

//딕셔너리 요소 추가 갱신 
var countryCodes3:Dictionary<String, String> = ["KR":"Korea, Republic of", "US":"United States", "FR":"France"]
countryCodes3["KR"] = "Korea"
countryCodes3["IT"] = "Italy"

//updateValue함수 사용법 
//입력되었는지 혹은 업데이트 되었는지를 체크한다.
if let oldValue = countryCodes3.updateValue("Korea", forKey:"KR") {
    println("Updated!")
} else {
    println("Inserted")
}

//딕셔너리 요소 삭제 
var countryCodes4:Dictionary<String, String> = ["KR":"Korea, Republic of", "US":"United States", "FR":"France"]
countryCodes["US"] = nil
println(countryCodes4)

//removeValueForKey사용
var countryCodes5:Dictionary<String, String> = ["KR":"Korea, Republic of", "US":"United States", "FR":"France"]
if let removedValue = countryCodes5.removeValueForKey("US") {
    println("US key value removed")
}

//모든 요소를 삭제
countryCodes5.removeAll(keepCapacity: false)
println(countryCodes5.count)

//딕셔너리 순회
var countryCodes6:Dictionary<String, String> = ["KR":"Korea, Republic of", "US":"United States", "FR":"France"]
for (countryCoude, countryName) in countryCodes6 {
    println("\(countryCoude) - \(countryName)")
}

//딕셔너리 순회
for countryCode in countryCodes6.keys {
    println(countryCode)
}

//딕셔너리 순회 
for countryName in countryCodes6.values {
    println(countryName)
}

//배열로 직접 받아서 처리하는 경우
let codes = Array(countryCodes6.keys)
let names = Array(countryCodes6.values)



댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.

송길영 작가의 신간 - "경량문명의 탄생" 독서 후기입니다.

  문명이 바뀌고 있다는 것을 누구나 감지하고 있습니다. ㅎㅎ 중량문명이 아닌 경량문명의 시대가 도래하고 있습니다. 수업을 하면서, 또는 친구들과 대화하면서 문명이 바뀌고 있다는 말을 자주했는데 정말 설명하기 좋은 단어가 바로 "경량문명...