Swift 泛型控制台输出

Posted

技术标签:

【中文标题】Swift 泛型控制台输出【英文标题】:Swift Generics Console Output 【发布时间】:2014-09-21 12:14:38 【问题描述】:

在 Playground 中启用此类后,我丢失了在此类上方编写的所有控制台输出。这有什么问题?奇怪的是,它在 switch 语句中显示错误“预期模式”一段时间,然后错误消失了

class Cart<T> 
    var customerName: String
    var customerEmail: String
    var items: [T]
    var itemCount: Int 
        return items.count
    
    var promoCode: String? = nil
    init(customerName: String, customerEmail: String)
        self.customerName = customerName
        self.customerEmail = customerEmail
        items = [T]()
    

    func add (item: T) -> () 
        items.append(item)
    

    func clear () -> () 
        items.removeAll(keepCapacity: false)
    

    func remove (position: Int) -> () 
        items.removeAtIndex(position - 1)
    

    func getPromoCodeDisplay () -> (String) 
        if let x = promoCode 
            return "Your promo code is \(x)"
         else 
            return "You do not have a promo code"
        
    

    func getCartStatus () -> (String) 
        switch itemCount 
        case : 0
        return "You have no items in your cart."
        case : 1...3
        return "You have \(itemCount) items in your cart."
        default :
            return "You are an awesome customer!!"
        
    

【问题讨论】:

【参考方案1】:

您在 case 语句中的冒号 (:) 位置错误。

func getCartStatus () -> (String) 
    switch itemCount 
    case 0 :
    return "You have no items in your cart."
    case 1...3 :
    return "You have \(itemCount) items in your cart."
    default :
        return "You are an awesome customer!!"
    

【讨论】:

以上是关于Swift 泛型控制台输出的主要内容,如果未能解决你的问题,请参考以下文章

使用 Swift Playground 无法在助手编辑器中查看控制台输出

金属着色语言 - (控制台)输出?

AudioUnit - 在 Swift 中控制左声道和右声道输出

Swift 日志输出类 SwiftyBeaver

泛型学习由浅入深

Swift:线程 1:信号 SIGABRT