29: WordScramble, part 1

그루두·2024년 5월 12일
0

100 days of SwiftUI

목록 보기
38/108

100 days of swiftui: 29
https://www.hackingwithswift.com/100/swiftui/29

List

List는 Form과 같은 테마를 가지고 있고 요소들을 목록으로 나타낸다. 그리고 아래 사진처럼 스타일을 지정할 수 있다.

struct ContentView: View {
    let cats = ["cheese", "tabby", "tuxedo", "chaos"]
    var body: some View {
        List{
            Section("cats") {
                ForEach(cats, id: \.self) {
                    Text($0)
                }
            }
            Section("numbers") {
                Text("1")
                Text("2")
                Text("3")
            }
        }
        .listStyle(.grouped)
    }
}

또는 ForEach문처럼 사용할 수도 있다.

struct ContentView: View {
    let cats = ["cheese", "tabby", "tuxedo", "chaos"]
    var body: some View {
        List(cats, id: \.self) {
            Text($0)
        }
    }
}

코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/ec2864f4696461e273ae33b43be418cc3a8dbdd7

Bundle

swiftui에서는 이미지를 제외한 resource는 이미지와 달리 추가 과정이 필요하다. resource와 그의 파일 형태를 필요로 한다. xcode는 ios, macos 앱을 실행할 때 자동으로 Bundle이라는 것을 만들고 여기에 파일들을 저장할 수 있도록한다.

Bundle에 파일들을 저장하면서 URL이라는 데이터 타입을 사용하는데, 웹주소뿐만 아니라 파일의 위치도 저장할 수 있다.

    func testBundles() {
        if let fileUrl = Bundle.main.url(forResource: "somefile", withExtension: "txt") {
            if let fileContents = try? String(contentsOf: fileUrl) {
                // file is loaded into a string
            }
        }
    }

nil일 경우를 대비하여 코드를 작성하면 된다.

코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/a8e1a23f6f639bc1f6a054fcf915bb36f510149f

with String

swiftui는 String을 다루는 여러 도구를 제공한다.

let input = """
            a
            b
            c
            """
let letters = input.components(separatedBy: "\n")
let letter = letters.randomElement()

components()는 위 input을 특정 문자를 기준으로 분리하여 array에 담는다. 그리고 randomElement()는 그 배열에서 무작위로 한 요소를 반환한다. 빈 문자열을 분리한다면 반환하는 값이 없을 수도 있기 때문에 nil의 경우도 고려해야 한다.

let trimmed = letter?.trimmingCharacters(in: .whitespacesAndNewlines)

trimmingCharacters()는 문자열의 시작과 끝의 공백(space, tab, line breaks)을 제거한다.

그리고 스펠링을 체크하는 도구인 UITextChecker도 있다.

💡 UI로 시작하는 도구들은 UIKit에서 유래했고, Objective-C로 만들어졌다.

		// 1
        let word = "swift"
        let checker = UITextChecker()
        // 2
        let range = NSRange(location: 0, length: word.utf16.count)
        // 3
        let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
        // 4
        let allGood = misspelledRange.location == NSNotFound
        print(allGood)
  1. 스펠링을 체크할 String과 UITextChecker를 instance를 만든다.
  2. checker에게 얼마만큼의 String을 체크하고 싶은지 알려준다. 다만 Objective-C는 swiftui처럼 작동하지 않기 때문에 Objective-C의 range를 적용시켜야 한다. 이때 utf16라는 연결다리를 이용한다.
  3. checker에게 어떤 단어를 얼마만큼 어떤 언어를 기준으로 스펠링 검사를 하라고 명령한다.
  4. 검사가 종료되면 스펠링 오류에 대한 값을 지닌다. 스펠링 오류가 없으면 NSNotFound로 설정된다.

코드 파일
https://github.com/treesofgroo/Ios-WordScramble/commit/96174c46ed5320d45e283c393780436fe799eab9

profile
계속 해보자

0개의 댓글

관련 채용 정보