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]

댓글 없음:

댓글 쓰기

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

요즘 새로운 과정을 기획하면서 react.js + next.js를 OpenAI API와 같이 사용하는 과정을 만들고 있습니다. ㅎㅎ

 오랜만에 웹 기술들을 공부하니 재미있네요. ㅎㅎ  쭉 파이썬 과정들을 운영하고 있었는데 좀 더 범위를 넓혀서 아이폰 앱 개발과정 with ChatGPT,  웹 프로그래밍 with ChatGPT, AI시대의 AI어시스턴트 활용하기와 같은 글을 쓰고, ...