대충 그린 설계도.
// 마트(Mart) 클래스 (부모 클래스)
class Mart {
}
// 제품(Product) 클래스 (자식 클래스: 부모클래스를 상속)
class Product: Mart {
var brand: String
var itemName: String
var itemCode: Int
var availableStock: Int
var itemPrice: Double
}
// 장바구니(Cart) 클래스 (자식 클래스)
class Cart {}
// 할인 유형(Discount Type) 이넘
enum DiscountType {
case odd
case even
case brand
case individual
case membership
}
// 결제(Payment) 클래스 (자식 클래스)
class Payment {}
앗! 이제 다시 보니 마트에서 물건을 사는 것은 2주차 과제였고 3주차 과제 가이드 라인을 다시 확인해보니 추가되거나 축소된 내용이 있어서 여기에 다시 정리해본다.
- 다이어그램을 이용해 설계하고 그 설계를 기반으로 코드를 작성할 것 (어려운 경우, 주석 작성 OK)
- 만들어야 할 클래스 :
User / ShoppingCart / ShoppingMall / Payment / Product- 주어진 상황:
1. 쿠팡 쇼핑몰에서 유저가 로그아웃 상태에서 장바구니에 물건들을 담습니다.
2. 유저는 장바구니에서 각각의 구매 품목 이름과 수량, 가격, 브랜드를 확인할 수 있습니다. (print 형태로)
3. 유저는 장바구니에서 구매할 물건의 총 개수와 총액을 확인할 수 있습니다.
- 장바구니에는 로그인 유저가 이전에 담아놓은 품목들이 있는 상태입니다.(더미값 넣기)
- 유저가 로그인을 한 후에 로그아웃상태에서 담았던 장바구니에 있던 제품들을 유저의 장바구니(Level2 - 1 장바구니)에 추가합니다.
- 만들어야 할 클래스 :
User / ShoppingCart / ShoppingMall / Payment / Product 클래스 또는 Product 프로토콜- 상속 또는 프로토콜 둘 중에 하나를 채택하여 설계/구현
다시 한번 그린 설계도
<작성코드>
// 상품구입시 공통적으로 쓰이는 결제수단
enum PaymentMethod {
case cash // 현금
case creditCard // 카드
case giftCard // 상품권
}
class product {
private(set) var id: Int
private(set) var name: String
private(set) var price: Double
init(id: Int, name: String, price: Double) {
self.id = id
self.name = name
self.price = price
}
func setId(_ newId: Int) {
self.id = newId
}
}
class User {
var userStatus: Bool // 로그인 여부(로그인시: true, 로그아웃시: false)
var userName: String? // 고객이름(비회원이거나 로그아웃상태인 경우 nil)
var userId: Int? // 회원번호(이하 동일)
init(userStatus: Bool, userName: String, userId: Int) {
self.userStatus = userStatus
self.userName = userName
self.userID = userId
}
func userStatusChanged(_ userStatusBool: Bool) -> Bool {
if userStatusBool == true {
return true
} else {
return false
}
}
}
class Cart {
private var items: [product: Int] = [:]
// 담긴 상품의 총상품수량
private var totalAmount: Int {
return items.count
}
// 담긴 상품의 총상품가격
private var totalPrice: Double = 0.0
init(items: [product]) {
addItems(items)
self.totalPrice = getTotalPrice()
}
// 품절상품 제거
func removeSoldOutProduct(_ items: [product]) {
for item in items {
if var soldout = self.items[item] {
soldout == 0
} else {
self.items[item] = 1
}
}
}
// 상품취소, 상품을 빼기
func subtractItems(_ items: [product]) {
for item in items {
if var nolongerwanted = self.items[item] {
nolongerwanted - 1
} else {
self.items[item] = 1
}
}
}
// 상품을 담기
func addItems(_ newItems: [product]) {
for item in newItems {
if var existed = self.items[item] {
existed += 1
} else {
self.items[item] = 1
}
}
}
// 카트에 담긴 상품을 보여줌(제품명, 담긴 수량)
func getCartList() -> [(String, Double)] {
var products: [(String, Double)] = []
for item in self.items {
let productName = item.key.name
let oneProductTotal = item.key.price * Double(item.value)
products.append((productName, oneProductTotal))
}
return products
}
// 카트에 담긴 상품의 총갯수, 금액을 구함
func getPurchasingInfo() -> (Int, Double) {
return (totalAmount, getTotalPrice())
}
// 총상품가격 구하기
private func getTotalPrice() -> Double {
var total = 0.0
for item in self.items {
let oneProductTotal = item.key.price * Double(item.value)
total += oneProductTotal
}
}
}
class Payment {
func chooseMethod(of paymentMethod: PaymentMethod) {
switch paymentMethod {
case .cash:
print("현금 결제 선택")
// 현금 결제 로직
case .creditCard:
print("카드 결제 선택")
// 카드 결제 로직
case .giftCard:
print("상품권 결제 선택")
// 상품권 결제 로직
}
}
}
// 더미데이터
let shirt = Product(id: 1230, name: "Shirt", price: 25.99)
let skirt = Product(id: 1231, name: "Skirt", price: 19.00)
let trousers = Product(id: 0123, name: "Trousers", Price: 35.00)
let socks = Product(id:3456, name: "Socks", Price: 1.99)
let initialList: [product] = [shirt, skirt, trousers, socks]
let shoppingCart = ShoppingCart(items: initialList)
var shoppingList =
print("쇼핑목록: ", shoppingCart.getCartList())
print("장바구니 정보: ", shoppingCart.getPurchasingInfo())
// 쇼핑카트에 상품을 추가로 담기
shoppingCart.addItems([Product(id: 6789, name: "belt", price: 8.99),
Product(id: 9076, name: "jacket", price: 125.00)])
print("쇼핑목록: ", shoppingCart.getCartList())
print("장바구니 정보: ", shoppingCart.getPurchasingInfo())
좀 더 매끄러운 개연성을 갖도록 코드를 작성하고 싶었으나 여기까지가 생각의 한계.
다른 정예반 수강생들은 과제에 얼마나 시간이 걸리는지 궁금하다.
왜냐하면 나는 오늘 이 코드를 적는데에만 하루 종일의 시간이 걸렸기 때문이다. 그것도 혼자만의 힘으로 작성한 것이 아니라 지난주 강의때 튜터님이 설계하신 코드를 보고 그것을 바탕으로 약간씩만 수정을 한 정도이다.
구조체였던 Product를 클래스 구현으로 바꾸어주고,
User의 로그인 상태 유무를 나타내기 위한 메서드를 넣어보았다.
원래 구조체였던 Product: Hashable 을 클래스로 수정하면서 마주한 오류다.
여기서 어떻게 더 수정해주는 것이 적절한 방법일까?
주말에 시간이 가능하다면 혼자 더 고민해보려 한다. 다음주 과제 피드백과 해설강의가 벌써부터 궁금해진다.
오늘의 공부는 여기까지.
어렵지만 재밌는 코딩의 세계다. 🤓😚
어렵지만 재밌어졌다니 !! 😭👍🏻👍🏻