Structure 예제
편의점에 대한 구조체를 만들어보자!
다음 코드는 현재 내 위치에서 가장 가까운 편의점을 찾는 코드이다.
먼저 편의점의 위치와 이름을 관리하는 구조체를 생성해보자.
Location structure는 위치 좌표에 대한 것이고, Store structure는 편의점의 위치와 이름에 대한 것이다.
이때 Object는 structure로 구현될 수 있다는 것을 기억해본다면, 구조체 안에는 데이터 뿐만 아니라 메소드도 들어갈 수 있다는 걸 알 수 있다.
struct Location {
let x: Int
let y: Int
}
struct Store {
let loc: Location
let name: String
let deliveryRange = 2.0
func isDeliverable(userLoc: Location) -> Bool {
let distanceToStore = distance(current: userLoc, target: self.loc)
return distanceToStore < deliveryRange
}
}
편의점 객체를 생성해보자.
let store1 = (x: 3, y: 5, name: "gs")
let store2 = (x: 4, y: 6, name: "seven")
let store3 = (x: 1, y: 7, name: "cu")
위의 store 객체는 Tuple 타입이다. 해당 Tuple 구성을 보면 데이터 간에 어떤 연간 관계를 갖고 있는지 파악하기 어렵다. 딱 보고서 x, y, name이 어떤 관계로 묶여있는지 파악이 안된다!
그럼 같은 내용을 Structure를 이용하여 편의점 객체를 생성해보도록 하자.
let store1 = Store(loc: Location(x: 3, y: 5), name: "gs")
let store2 = Store(loc: Location(x: 4, y: 6), name: "seven")
let store3 = Store(loc: Location(x: 1, y: 7), name: "cu")
Tuple로 생성된 객체와 비교해보더라도 Structure로 생성된 객체가 데이터 간의 연간 관계를 더 쉽게 파악할 수 있다는 것을 알 수 있다.
이러한 점 때문에 Structure를 사용하는 것이다.
이처럼 Structure를 사용하면 다음과 같은 이점이 있다.
- 먼저, 가독성이 좋아진다. 타입 이름들을 통하여 데이터의 역할을 쉽게 파악할 수 있다.
- 그리고 재사용성이 좋아진다.
나머지 코드도 마저 보도록 하자.
//거리구하는 함수
func distance(current: Location, target: Location) -> Double {
//피타고라스
let distanceX = Double(target.x - current.y)
let distanceY = Double(target.y - current.y)
let distance = sqrt(distanceX*distanceX + distanceY*distanceY)
return distance
}
// 가장 가까운 스토어 구해서 프린트 하는 함수
func printClosestStore(currentLocation: Location, stores: [Store]) {
var closestStoreName: String = ""
var closestStoreDistance = Double.infinity
var isDeliverable = false
for store in stores{
let distanceToStore = distance(current: currentLocation, target: store.loc)
closestStoreDistance = min(distanceToStore, closestStoreDistance)
if closestStoreDistance == distanceToStore {
closestStoreName = store.name
isDeliverable = store.isDeliverable(userLoc: currentLocation)
}
}
print("Closest store: \(closestStoreName), isDeliverable: \(isDeliverable)")
}
let myLocation = Location(x: 2, y:5)
let stores = [store1, store2, store3]
printClosestStore(currentLocation: myLocation, stores: stores)
패스트캠퍼스 [직장인 실무교육]
프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.
fastcampus.co.kr
본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.
'iOS > iOS 앱 개발 올인원 패키지 Online' 카테고리의 다른 글
[iOS] 패스트캠퍼스 챌린지 19일차 - Structure(4).Property vs. Method (0) | 2021.09.24 |
---|---|
[iOS] 패스트캠퍼스 챌린지 18일차 - Structure(3) (0) | 2021.09.23 |
[iOS] 패스트캠퍼스 챌린지 16일차 - Structure(1). Structure vs. Class (0) | 2021.09.21 |
[iOS] 패스트캠퍼스 챌린지 15일차 - Closure(2) (0) | 2021.09.20 |
[iOS] 패스트캠퍼스 챌린지 14일차 - Closure(1) (0) | 2021.09.19 |