본문 바로가기

14일 만에 아이폰 앱 만들기

14일 만에 아이폰 앱 만들기 챌린지(8) - Structures

14일 만에 아이폰 앱 만들기 챌린지(8) - Structures

 

플레이그라운드를 열도록 하자. 

 

struct는 다음과 같이 선언할 수 있다.

struct MyStruct {

}

struct의 이름은 보통 대문자로 시작하고 CamelCase 형태(ex. MyApple, YourBook, ThisIsMyPhone)이다. 자기만 혼자서 프로그래밍할 거라면 상관없지만 누군가 나의 코드를 보거나 협업을 하는 거라면 이 규칙을 지키는 것을 권장한다.

 

struct 안에는 상수나 변수 등을 넣을 수 있다. 물론 이 상수나 변수를 다시 사용할 수 있다. 

함수도 넣을 수 있다.

 

ChatView라는 struct를 만들어 자세히 알아보자.

struct ChatView {
  // Variables and Constants (Property)
  var message:String = ""
  
  // View Code for this screen.
  
  // Functions (Method)
  func sendChat() {
    // Code to send the chat message
  }

}

 

ChatView라는 struct는 앱의 한 페이지를 위한 struct이다. ChatView는 채팅을 위한 화면이라고 생각하면 된다. 이 페이지 내에서는 메시지를 저장할 변수도 필요할 것이고, 메시지를 보내기 위한 함수도 필요할 것이다. 더 많은 것이 필요하겠지만 이 정도로 페이지를 구상한다고 가정할 때 struct는 위와 같이 될 것이다.

 

struct내에서 변수나 상수는 property라고 표현하고 struct내에서 함수는 메소드라고 표현한다.

 

sendChat 메소드는  message를 호출하여 사용할 수 있다. struct라는 같은 영역(scope)에 있기 때문이다. 여기서 scope란 용어는 잘 기억하자. 

 

sendChat에서 message를 호출하는 것을 보고 다른 메소드도 추가하여 message를 호출하게 해 보자.

 

struct ChatView {
  // Variables and Constants (Property)
  var message:String = ""
  
  // View Code for this screen.
  
  // Functions (Method)
  func sendChat() {
    // Code to send the chat message
    print(message)
  }
  
  func deleteChat() {
    print(message)
  }

}

sendChat과 deleteChat 모두 message를 호출하여 사용하고 있다. sturct 안에, 즉 같은 scope에 있기 때문에 message를 호출하여 사용할 수 있다.

 

sendChat과 deleteChat 메소드는 또 각각 scope를 가지고 있다. 다음 코드를 보도록 하자.

 

struct ChatView {
  // Variables and Constants (Property)
  var message:String = ""
  
  // View Code for this screen.
  
  // Functions (Method)
  func sendChat() {
     var prefix = "Johnson Says: "
  
    // Code to send the chat message
    print(message)
  }
  
  func deleteChat() {
    print(prefix  + message) // 오류 발생
  }

}

sendChat메소드 내에서 선언된 변수 prefix를 deleteChat에서 사용하려고 하니 오류가 발생한다. 두 메소드 모두 사용 가능한 상수나 변수를 만드는 방법이 있다. ChatView의 property로 만드는 것이다.

 

struct ChatView {
  // Variables and Constants (Property)
  var message:String = ""
  var prefix = "Johnson Says: "

  
  // View Code for this screen.
  
  // Functions (Method)
  func sendChat() {  
    // Code to send the chat message
    print(prefix + message)
  }
  
  func deleteChat() {
    print(prefix  + message)
  }

}

 

property는 값뿐만 아니라 계산된 값(computed property)을 가질 수도 있다. 예시를 보도록 하자.

 

 

struct ChatView {
  // Variables and Constants (Property)
  var message:String = ""
  var messageWithPrefix:String {
    return "Jhonson says : " + message
  }

  
  // View Code for this screen.
  
  // Functions (Method)
  func sendChat() {  
    // Code to send the chat message
    print(messageWithPrefix)
  }
  
  func deleteChat() {
    print(messageWithPrefix)
  }

}

 

messageWithPrefix라는 property를 보면 마치 함수처럼 문자열(텍스트)을  return하는 것을 볼 수 있다.

아래 메소드에서 messageWithPrefix를 호출하면  해당 값이 계산되고 쓰인다.

 

위 코드와 같이 messageWithPrefix 내부의 코드가 한 줄 일 경우 return을 생략할 수도 있다.

struct ChatView {
  // Variables and Constants (Property)
  var message:String = ""
  var messageWithPrefix:String {
    "Jhonson says : " + message // return 생략
  }

  
  // View Code for this screen.
  
  // Functions (Method)
  func sendChat() {  
    // Code to send the chat message
    print(messageWithPrefix)
  }
  
  func deleteChat() {
    print(messageWithPrefix)
  }

}

두 줄 이상일 때는 return을 꼭 사용해주어야 한다.

 

지금까지 간단한 struct를 선언하는 것, property와 method, scope, Computed Property를 알아 보았다.

 

다음은 Car Struct를 만들어 보는 것이다.

 

Declare a struct called "Car"

Declare 4 properties called make, model, year and details

Assign String data to the make, model and year properties (use whatever values you want)

Make the details property a computed property that returns a String with the year, make and model. (For example, "1999 Toyota Camry")

(Hint: You can use the + operator to add strings together. This is also known as concatenation)

Make all 4 properties have the private access level

Finally, declare a method called getDetails which returns the value of the details property.

 

 

, 스스로 만들어보고 아래 펼쳐서 내가 작성한 솔루션과 비교해보기 바란다.

더보기
struct Car{
  var make:String = "KIA"
  var model:String = "Sportage"
  var year:String = "2020"
  var details:String{
    year + " " +  make + " " + model
  }
  
  func getDetails() -> String{
    return details
  }

}

 

여기까지 하면 끝!