Skip to content

Study\#20\Boolean, String interpolation 학습#21

Open
heygrv wants to merge 14 commits into
mainfrom
#20-Week0]Boolean,-String-interpolation
Open

Study\#20\Boolean, String interpolation 학습#21
heygrv wants to merge 14 commits into
mainfrom
#20-Week0]Boolean,-String-interpolation

Conversation

@heygrv
Copy link
Copy Markdown
Contributor

@heygrv heygrv commented Jun 6, 2025

학습

🌱 Challenge 정보

📌 Check List

  • 시간을 잘 엄수했나요?
  • GQ의 답을 찾아냈나요?
  • 다른 스터디원들의 PR을 모두 확인했나요?

✨ 나의 Finding & Synthesis

  • 알게 된 점 1. Boolean은 true/false 연산자임.
  • 알게 된 점 2. Boolean은 사칙연산을 할 수 없음.
  • 알게 된 점 3. Boolean은 !, .toggle() 로 true를 false로 또는 false를 true로 바꿀 수 있음.
  • 알게 된 점 4. 문자열을 결합할 때는 "+"나 string interpolation "()"을 사용할 수 있음.
  • 알게 된 점 5. "+"보다 string interpolation "()"이 효율적임.
  • 알게 된 점 6. string interpolation "()"은 문자간 결합 뿐 아니라 문자와 숫자(Integer, Double) 간 결합도 용이함.
  • 알게 된 점 7. string interpolation "()"은 숫자의 사칙연산 가능.
  • 알게 된 점 8. Swift에서 string interpolation "()"을 사용하는 것은 사용자로부터 데이터를 받아 처리해야 하기 때문임.

✅ 팀원 확인

⚡ 리뷰어 확인

  • 학습 내용 검토 완료
  • 추가 학습 필요 시 코멘트

⁉️ 새롭게 생긴 Curiosity

  • 궁금한 점 1 Boolean 외의 데이터 타입은 어떤 것들이 있을까?
  • 궁금한 점 2 데이터 타입들을 사용할 때 주의할 점은 어떤 것들이 있을까?

heygrv added 2 commits June 6, 2025 23:12
Boolean, String Interpolation �학습
@heygrv heygrv changed the title Study\#20\Boolean, String Interpolation 학습 Study\#20\Boolean 학습 Jun 14, 2025
@heygrv
Copy link
Copy Markdown
Contributor Author

heygrv commented Jun 14, 2025

Q. Boolean을 소화하는 방식에는 어떤 것들이 있는지?

A. Boolen은 UI의 상태를 조건에 따라 제어할 때 자주 사용함.
1. @State와 조건부 렌더링

struct ContentView: View {
@State private var isOn = false          // @State는 Boolean을 저장하고 UI와 연결.

var body: some View {
    Toggle("Power", isOn: $isOn)

    if isOn {                                            // if isOn으로 뷰의 표시 여부를 조건부로 결정.
        Text("System is ON")
    } else {
        Text("System is OFF")
        }
   }
}

2. 뷰 Modifier에서 Boolean 활용

struct ContentView: View {
@State private var isCritical = true

 var body: some View {
Text("Caution")
    .foregroundColor(isCritical ? .red : .primary)
    .bold(isCritical)
  • Boolean 값을 통해 .foregroundColor, .bold() 등의 modifier를 동적으로 적용.

3. .opacity, .disabled, .hidden 같은 속성 제어

struct ContentView: View {
 @State private var isFormValid = true

 func submit() {
  isFormValid.toggle()    // 버튼 누르면 true ↔ false 바뀜
 }
 var body: some View {
  Button("Submit", action: submit)
      .disabled(!isFormValid)
      .opacity(isFormValid ? 1.0 : 0.5)
 }
}
  • Boolean 값에 따라 사용자의 상호작용을 제한하거나 시각적으로 처리.

4. Binding을 이용한 하위 뷰와의 상태 공유

struct ParentView: View {
    @State private var isPresented = false

    var body: some View {
        ChildView(isPresented: $isPresented)
    }
}

struct ChildView: View {
    @Binding var isPresented: Bool

    var body: some View {
        Toggle("Show modal", isOn: $isPresented)
    }
}
  • @binding은 상위 뷰의 Boolean 값을 하위 뷰에서 공유 및 조작 가능하게 해줌.

5. 애니메이션 조건에 사용

withAnimation {
    isExpanded.toggle()
}

6. sheet, alert, popover 등에서 Boolean로 제어

@State private var showSheet = false

var body: some View {
    Button("Show Sheet") {
        showSheet = true
    }
    .sheet(isPresented: $showSheet) {
        Text("This is a modal sheet")
    }
}
  • isPresented: Binding은 sheet나 alert 등 표현 여부에 직접 사용됨.

7. toggle() 메서드로 간결한 상태 전환

Button("Toggle") {
    isActive.toggle()
}

@heygrv heygrv closed this Jun 14, 2025
@heygrv heygrv reopened this Jun 14, 2025
@heygrv
Copy link
Copy Markdown
Contributor Author

heygrv commented Jun 14, 2025

Q. Boolean과 enum은 각각 어떤 때 사용하는가?

A. Boolean: 상태가 단순한 두 가지 값
enum: 상태가 단순한 두 가지 값 이상, enum이 더 명확하고 확장성이 큼.
예: enum AuthState { case loggedOut, loggedIn, loading }

@heygrv
Copy link
Copy Markdown
Contributor Author

heygrv commented Jun 15, 2025

Q. .toggle() 에서 () 안에 들어갈 수 있는 게 뭐가 있나요?

A. 아무 것도 올 수 없어요.
.toggle()은 매개변수가 없는 메서드입니다.
괄호 안에 값을 넣을 수 없고, 넣으면 컴파일 에러가 납니다.

@State private var isOn = false

Button("Toggle") {
   isOn.toggle()  // true ↔︎ false 전환
}
  • 옵셔널에는 직접 쓸 수 없어요:
var maybeFlag: Bool? = true
maybeFlag?.toggle()     // ✅ OK (Optional Chaining => 값이 있으면 'toggle()' 실행, 값이 없으면 아무 일도 안 일어남 => "만약 maybeFlag 안에 값이 있다면 그 값을 바꿔줘"의 의미.)
maybeFlag.toggle()      // ❌ Error! Bool?엔 toggle() 없음

Q. 옵셔널에 쓰려면?

A. 옵셔널을 확실하게 풀어주면 돼요!

✅ 방법 1: if let(var)으로 안전하게 꺼내기

swift
if var unwrapped = maybeFlag {  // 1
    unwrapped.toggle()                  // 2
    maybeFlag = unwrapped         // 3
}
•	값이 있을 때만 꺼내서 바꾸고, 다시 넣어줌
•	값을 꺼내서 직접 처리하면, 더 복잡한 작업(예: 로그 찍기, 조건 확인 등)을 함께 할 수 있음.

1
• maybeFlag는 옵셔널 Bool로 값이 true, false, nil의 세 가지 중 하나.
• “만약 maybeFlag 안에 값이 있으면, 그걸 꺼내서 unwrapped라는 이름으로 써볼게!”
• 만약 maybeFlag가 nil이면? → 아래 코드는 아예 실행되지 않음!
2
• unwrapped가 true 면 false로, false면 true로 값 변경.
3
• unwrapped를 다시 maybeFlag로 변경. 원래 값인 maybeFlag가 진짜로 바뀌게 됨.

✅ 방법 2: 옵셔널 체이닝 (?.)
maybeFlag?.toggle()
• 값이 있을 때만 알아서 바꿔줌
• 제일 간단하고 안전함!

✅ 방법 3: 기본값을 줌
(maybeFlag ?? false).toggle() // ❌ 이렇게 쓰면 바뀌는 건 복사본!
• 이건 값을 복사해서 바꾸는 거라 maybeFlag 자체는 바뀌지 않음.

✨ 정리
코드 | 작동 방식 | 안전함? | 실제 변수 값이 바뀌나?
maybeFlag?.toggle() | 값이 있을 때만 바꿈 | ✅ | ✅
maybeFlag.toggle() | 옵셔널엔 .toggle() 없음 (에러!) | ❌ | ❌
if let var ... | 값 꺼내서 바꾼 뒤 다시 넣음. | ✅ | ✅
(maybeFlag ?? false).toggle() | 복사된 값만 바뀜, 원본은 그대로 | ✅

@heygrv
Copy link
Copy Markdown
Contributor Author

heygrv commented Jun 15, 2025

Q. isMultiple(of: ) 과 비슷한 연산 메소드가 뭐가 있나요?

A. Swift의 BinaryInteger 프로토콜에서 제공하는 숫자나 컬렉션 등에 사용되는 의미 기반의 연산 메서드

✅ 숫자와 관련된 연산 메서드들

  1. isMultiple(of:)
    • 어떤 수가 특정 수의 배수인지 확인
    10.isMultiple(of: 5) // true

  2. truncatingRemainder(dividingBy:)
    • 실수(FloatingPoint)에서 나머지를 구할 때
    8.5.truncatingRemainder(dividingBy: 3.0) // 2.5

  3. quotientAndRemainder(dividingBy:)
    • 몫과 나머지를 한꺼번에 튜플로 반환

let result = 10.quotientAndRemainder(dividingBy: 3)
// result.quotient == 3, result.remainder == 1
  1. advanced(by:)
    • 특정 값만큼 더한 값을 반환 (Index, Int, Date 등)
    5.advanced(by: 3) // 8

  2. distance(to:)
    • 두 수(혹은 Index 등)의 거리 계산
    5.distance(to: 10) // 5

✅ 컬렉션 관련 연산 메서드

  1. contains(_:)
    • 특정 요소가 있는지 검사
    [1, 2, 3].contains(2) // true

  2. firstIndex(of:), lastIndex(of:)
    • 특정 요소의 인덱스를 반환
    ["a", "b", "c"].firstIndex(of: "b") // 1

  3. starts(with:), ends(with:)
    • 특정 패턴으로 시작하거나 끝나는지
    [1, 2, 3].starts(with: [1, 2]) // true

✅ 문자열 관련

  1. hasPrefix(:), hasSuffix(:)
    • 문자열이 특정 접두어나 접미어를 갖는지
    "SwiftUI".hasPrefix("Swift") // true

  2. localizedStandardContains(_:)
    • 대소문자 구분 없이 포함 여부 검색
    "Hello World".localizedStandardContains("world") // true

✅ 비교 및 판별 관련

  1. clamped(to:)
    • 범위 내로 값을 제한
    let value = 15.clamped(to: 0...10) // 10

  2. signum()
    • 수의 부호를 반환 (-1, 0, 1 중 하나)
    (-5).signum() // -1

@heygrv
Copy link
Copy Markdown
Contributor Author

heygrv commented Jun 15, 2025

Q. isMultiple(of:)은 부동소수점(Float, Double)에도 사용할 수 있어요?

A. 아니요. isMultiple(of:)는 BinaryInteger 타입(Int 등) 전용이에요. 실수에는 truncatingRemainder(dividingBy:)를 사용하세요.

@heygrv
Copy link
Copy Markdown
Contributor Author

heygrv commented Jun 15, 2025

isMultiple(of: )로 짝수, 홀수 판별식을 만들 수 있음.

extension Int {
    var isEven: Bool { self.isMultiple(of: 2) }
    var isOdd: Bool { !isEven }
}

@heygrv
Copy link
Copy Markdown
Contributor Author

heygrv commented Jun 15, 2025

isMultiple(of:)를 %보다 권장.
가독성과 정확성 때문. isMultiple(of:)는 명확한 의도를 전달하고, 음수 처리도 직관적.

@heygrv heygrv changed the title Study\#20\Boolean 학습 Study\#20\Boolean, String interpolation 학습 Jun 15, 2025
Copy link
Copy Markdown
Contributor Author

@heygrv heygrv left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boolean 분리

@heygrv heygrv self-assigned this Jun 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant