-
렛츠스위프트_60호_What’s new in Swift 5.7 | by Md. Ibrahim HassaniOS/메일링 서비스 번역 2022. 8. 17. 09:56
렛츠 스위프트 메일링 리스트 가입은 >가입하기 링크<
swift 5.7에서 새로운 점
스위프트를 향한 애플의 비전은 효율적으로 perform하고, 확장 가능해지는 것이었다. swift 5.7은 거대한 변화를 겪었다, to improve language performance와 quality of life improvements, if let 같은 shorthand 문법처럼.
자 swift의 새로운 release의 변화점과 개선점으로 깊게 들어가보자.
SPM 개선점들
이제, SPM은 새로운 보안 프로토콜을 갖는다, TOFU( Trust on First Use ), 첫번째 다운로드에 package의 지문이 기록되며, 이후의 다운로드들도 이 지문을 validate한다. 스위프트는 이제, module disambiguation(모듈 명확성? 모듈 비모호성?) 덕분에, 프로그램에서 같은 이름을 공유하는 다수의 모듈을 허가한다
더작고 더 빠른 standard library
이제, Swift standard library는 더 작고 더 빠르다. 더 작고 더 빠른 binaries는 event-driven 서버 solutions를 구동할 때, 큰 benefit이다.
더 빠른 빌드와 app launch 시간
Swift 5.7은 병렬화된 빌드와 generics의 빠른 타입 checking덕에 더빠른 빌드시간을 갖게됨.
Protocol checks는 이제 cached되고, app launch time을 줄인다. Swift의 초기버전에서는 프로토콜들은 app launch하는 매번 계산되었다.
Swift Language Usability
optional unwrapping을 위한 축약
if let, guard let, while let 에서 변수명의 반복없이 옵셔널 변수를 unwrapping하는 축약이 생김
if let workingDirectoryMailmapURL { // if let workingDirectoryMailmapURL = working... { print (workingDirectoryMailmapURL) } while let workingDirectoryMailmapURL { print (workingDirectoryMailmapURL) break } guard let workingDirectoryMailmapURL else { return } print (workingDirectoryMailmapURL)
복잡한 클로져들을 위한 강화된 타입 추론
Swift의 클로저들을 위한 타입 추론이 강화됨. 이제는 아래와 같은 복잡한 클로저의 반환 type을 추론 할 수 있음.
let scores = [100, 80, 85] let results = scores.map { score in if score >= 85 { return "\(score)%: Pass" } else { return "\(score)%: Fail" } }
Swift5에서는 안돼요 C API와 강화된 interoperability(상호 운용성)
설계적으로, Swift는 type, memory-safety하고, 절대 자동적으로 다른 타입들의 포인터간 convert가 일어나지 않는다. 이 행동은 C 특정한 포인터의 conversion을 허락하는 C와 대조된다. 초기에, 이는 Swift에서 C APIs를 사용하는데 문제를 야기했으므로, Swift는 현재 imported된 functions and methods를 호출하는데 사용하는 별도의 규칙들을 갖는다. 이것은 C에서는 합법일지라도, Swift에서 불법인, Pointer conversion을 가능하게 한다.
더 나은 문자열 parsing with Regex
정규표현식은 pattern matching과 문자열 조작을 위한 강력한 tool이다. Regex는 매우 compact하고, 가끔 이해하고 debug 하기 어렵다.
이제 우리는 regex를 만드는 세가지 방법을 갖는다.
아래의 문자열에서 #로 시작하는 어떤 단어를 추출하는 regex를 작성하는 것으로써 탐색해보자.
let tweet = """I finally made it to the end of my #WWDC22 video watch list, so I wrote up my impressions of the event, discussed my top 10 session videos, put forward some session suggestions for folks who have limited time, and laid out my hopes for #WWDC23."""
1) 문자열로 부터 Regex만들기
초기 버전의 Swift에서, 우리는 아래와 같은 NSRegularExpression 사용했다.
if let regex = try? NSRegularExpression(pattern: "#[a-zA-Z0-9_]") { let range = NSRange(location: 0, length: tweet.count) let matches = regex.matches(in: tweet, range: range) for match in matches { let lowerBound = String.Index(utf16Offset: match.range.lowerBound, in: tweet) let upperBound = String.Index(utf16Offset: match.range.upperBound, in: tweet) let hashTag = tweet[lowerBound ..< upperBound] print (hashTag) } }
Swift 6.7에서 문법은 더 간결해진다.
import RegexBuilder if let regex = try? Regex("#[a-zA-Z0-9_]+") { let matches = tweet.matches(of: regex) for match in matches { let hashTag = tweet[match.range.lowerBound ..< match.range.upperBound] print (hashTag) } }
눈에 보이는 변경점
- import RegexBuilder
- NSRegularExpression -> Regex
- 패턴도 조금 다르다. 끝에 "+"가 붙었음. -> 이해가 잘 되지 않음.
- range를 선언이 불필요
- index를 추출해 낼 필요가 없음.
2) Regex literal로 Regex만들기
정규표현식을 만드는 가장 초기의 방법은, 아래에 보이듯이, regex literal을 사용하는 것이었다. regex literal은 compile-time check를 제공한다. 여기서 regex literal에 대해 더 배울수있다! (슬쩍 열어봤는데 벌써 읽기 무섭다)
import RegexBuilder let regex = /#[A-Za-z_0-9]+/ let matches = tweet.matches(of: regex) for match in matches { let hashTag = tweet[match.range.lowerBound ..< match.range.upperBound] print (hashTag) }
3) RegexBuilder를 사용하여 Regex만들기
SwiftUI와 매우 유사한, 정규표현식을 만들기 위한 expressive result-builder-based, domain-specific 언어를 제공한다. (번역이 좀... 맥락을 전달하기 어렵다.)
import RegexBuilder let regex = Regex { "#" OneOrMore { CharacterClass( ("a" ... "z"), ("0" ... "9"), ("_" ... "_") ) } } let matches = tweet.matches(of: regex) for match in matches { let hashTag = tweet[match.range.lowerBound ..< match.range.upperBound] print (hashTag) }
모든 Protocols를 위한 existential을 unlock
Swift5.7은, Associated type requirements가 있을 때, type으로서 protocol의 사용을 금지하는 것을 상당히 완화했다.
-> 원문 : Swift 5.7 significantly loosens the Swift’s ban on using protocols as types when they have associated type requirements
간단히 말해서, 아래의 코드가 허가 될 것이란 거다. (이건 확실하지 않은 내용 아닌가?)
let tvShow: [any Equatable] = ["Brooklyn", 99] // 글의 작성자는 이러한 예상을 하지만. 어디까지나 예상이 아닐까요? // 어느정도 loose하게 해주는지는 추가 조사하지않았습니당
Conclusions 저자의 끝내는 말
Swift 5.7 brings a lot of changes, quality of life improvements, and powerful new features like Swift regex, times and durations, distributed actors, and many others. It also paves the way for the way for full-thread safety, which would is planned to be released with Swift 6. The Swift team and collaborators are working on building interoperability with C++. Once implemented, we will be able to call C++ code directly from Swift.
Swift 5.7은 quality of life improvements와 Swift regex, times and durations, distributed actors, 그리고 many others와 같은 powerful new features와 많은 변화를 가져왔다. 이건 또한, Swift6에서 release될 full-threa safety로의 길도 닦았다. Swift팀과 collaborators는 C++과의 interoperability의 구현을 위해 작업중이다. 일단 구현된다면, 우리는 C++ code를 Swift에서 직접 호출 할 수 있을것이다.
References
What’s new in Swift — WWDC22
What's new in Swift 5.7 - Hacking with Swift
What’s the difference between any and some in Swift 5.7?
Meet Swift Regex - WWDC22 - Videos - Apple Developer