Swift function how to return nil

來源:互聯網
上載者:User

標籤:style   blog   java   color   os   io   

  這兩天在學習Stanford出品的iOS7的課程,這個課程去年也看過,但是看到第3課就不行了,滿篇的OC,把人都搞暈了。這段時間因為要寫個iOS的App,正好趕上了Swift問世,所以趁著這股勁繼續學習iOS的開發,把網上的一些視頻關於Swift的都看過和做過了,然後選擇看Stanford出品的這個視頻,把裡面OC實現的代碼用Swift實現一遍自己還是覺得比較有意義的,而且還能補充點iOS系統方面的知識。

  一切本都還順利,在看到第三課,有段代碼遇到點問題

代碼如下:

這一段通過牌堆Deck抽取一張牌card,當card為非nil時顯示內容,問題就處在card的傳回值。

代碼1:

var card:Card? = playDec.drawRandomCard()if card{    sender.setBackgroundImage(UIImage(named: "cardfront"),                    forState: UIControlState.Normal)    sender.setTitle(card!.contents, forState: UIControlState.Normal)}

下面是如何隨機抽取card的過程。

代碼2:

    func drawRandomCard() -> Card{        var randomCard: Card?        var count = cards.count        var temp = count + 1                        if(count != 0){            println("drawRandomCards------cards.count-\(count)")            var index:Int = Int(arc4random_uniform(UInt32(count)))            println("drawRandomCards------arc4random \(index)")                       println("drawRandomCard------index-\(index)")            randomCard  = cards[index]            cards.removeAtIndex(index)        }        return randomCard!    }

  當count==0的時候,牌堆中沒有牌,則函數返回nil,然後就代碼1就得到一個nil的card,從而不現實內容。以前寫java的時候這樣沒問題,但是Swift就不行了。因為引入了optional value的概念,此時非要return randomCard!   這個“!”表示randomCard不為空白。這不就扯了,我要返回空,你卻強制要非空。。

  那肯定有解決方案咯,代碼2 的函數模板是 ()->card  這裡可以看到,card不是optional value,所以必須為非空,所以想返回空值必須在card後面加個?,表示,可能為空白。所以正確的代碼是:

代碼3:

    func drawRandomCard() -> Card?{        var randomCard: Card?        var count = cards.count        var temp = count + 1                        if(count != 0){            println("drawRandomCards------cards.count-\(count)")            var index:Int = Int(arc4random_uniform(UInt32(count)))            println("drawRandomCards------arc4random \(index)")                       println("drawRandomCard------index-\(index)")            randomCard  = cards[index]            cards.removeAtIndex(index)        }        return randomCard    }

這樣就OK了,程式正常運行~~

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.