2017년 7월 16일 일요일

Swift 4에 새롭게 추가된 prefix, postfix, One Sided Range 연산자 입니다.

    @IBAction func btn3(_ sender: Any) {
        //Swift4에 추가된 prefix와 postfix버전
        //half open range와 closed range operator
        //배열의 절반에 접근하려면 기존에 사용하던 코드
        let array = [1,5,2,8,4,10]
        let halfIndex = (array.count - 1) / 2
        let openFirstHalf = array[0..<halfIndex]
        let closedFirstHalf = array[0...halfIndex]
        print(openFirstHalf)
        print(closedFirstHalf)
        
        //Swift4에서는 시작 인덱스를 명시하지 않고
        //접근할 수 있다.
        let openFirstSlice = array[..<halfIndex]
        let closedFirstSlice = array[...halfIndex]
        print("openFirstSlice: \(openFirstSlice)")
        print("closedFirstSlice: \(closedFirstSlice)")
        
        //range의 시작 인덱스를 삭제할 수 있다. 이유는 모든 배열 요소를
        //halfIndex를 통해 처리하도록 하기 때문이다.
        //기존 Swift3의 코드
        let nextIndex = halfIndex + 1
        let lastIndex = array.count - 1
        let openSecondHalf = array[nextIndex..<lastIndex + 1]
        let closedSecondHalf = array[nextIndex...lastIndex]
        print("openSecondHalf: \(openSecondHalf)")
        print("closedSecondHalf: \(closedSecondHalf)")
        
        //Swift4의 코드
        //half open range와 closed range operator를 사용하면서
        //끝부분을 생략할 수 있다. range의 end index를 생략할 수 있다.
        let closedSecondSlice = array[nextIndex...]
        print("closedSecondSlice: \(closedSecondSlice)")
        
        //one sided range 연산자
        //swift3에서 배열의 인덱스와 값을 출력할 경우
        for (index, value) in array.enumerated() {
            print("\(index + 1): \(value)")
        }
        //swift4에서는 아래와 같이 처리한다.
        //더이상 enumerated()메서드를 호출할 필요가 없고
        //시작 첨자를 1로 변경하고 싶으면 아래와 같이 한다.
        //zip함수를 사용해서 one sided range의 인덱스와 배열의 값을
        //결합한다.
        for (index, value) in zip(1..., array) {
            print("\(index): \(value)")
        }
        
        //One sided range는 switch구문과도 매칭된다.
        let favouriteNumber = 10
        switch favouriteNumber {
        case ..<0:
            print("Your favourite number is a negative one.")
        case 0...:
            print("Your favourite number is a positive one.")
        default:
            break
        }

        //기존 swap함수는 swapAt메서드를 사용하도록 한다.
        var numbers = [1,5,2,8,4,10]
        //swap(&numbers[0], &numbers[1])
        
        numbers.swapAt(0, 1)
        print("교환 이후:\(numbers)")
        

    }


[1, 5]
[1, 5, 2]
openFirstSlice: [1, 5]
closedFirstSlice: [1, 5, 2]
openSecondHalf: [8, 4, 10]
closedSecondHalf: [8, 4, 10]
closedSecondSlice: [8, 4, 10]
1: 1
2: 5
3: 2
4: 8
5: 4
6: 10
1: 1
2: 5
3: 2
4: 8
5: 4
6: 10
Your favourite number is a positive one.
교환 이후:[5, 1, 2, 8, 4, 10]

댓글 없음:

댓글 쓰기

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

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

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