Apple-CS-interview / iOS-CS-interview

7 stars 1 forks source link

some 키워드에 대해 설명하시오. #29

Open Do-hyun-Kim opened 1 year ago

Do-hyun-Kim commented 1 year ago

some 키워드에 대해 설명하시오.

Opaque Types

// some 키워드를 사용하지 않을 경우 오류 발생
// Use of protocol 'Collection' as a type must be written 'any Collection'
func makeCollections() -> some Collection {
    return [1,2,3]
}

some 키워드 간단한 사용법

func makeShape() -> some MyShape {
    return Circle()
}

func makeCollections() -> some Collection {
    return [1,2,3]
}

protocol Vehicle {
    var name: String { get }
    associatedtype FuelType

    func fillGasTank(with fuel: FuelType)
}

struct Car: Vehicle {
    let name: String = "JennyCar"

    func fillGasTank(with fuel: BMW) {
        print("Fill name: \(name) with \(fuel.name)")
    }

}

struct Bus: Vehicle {

    let name: String = "광진 05"

    func fillGasTank(with fuel: Village) {
        print("Fill name \(name) with \(fuel.name)")
    }
}

struct BMW {
    let name: String = "BMW"
}

struct Village {
    let name: String = "마을"
}

// 불투명한 함수 파라미터 타입
func OpaqueTypesWash(_ vehicle: some Vehicle) {
    print("세차 완료 \(vehicle.name)")
}

let someVehicle: [some Vehicle] = [Car(), Car(), Car(), Car()]
someVehicle.forEach { OpaqueTypesWash($0)}

📝 참고 사이트

ronick-grammer commented 12 months ago

some 키워드란

protocol Shape {
    func describe() -> String
}

struct Square: Shape {
    func describe() -> String {
        return "I'm a square. My four sides have the same lengths."
    }
}

struct Circle: Shape {
    func describe() -> String {
        return "I'm a circle. I look like a perfectly round apple pie."
    }
}

func makeShape() -> some Shape {
  return Circle()
}

let shape = makeShape()
print(shape.describe())

// "I'm a circle. I look like a perfectly round apple pie."

Generic과 some의 차이점

📝 참고 사이트