中文字幕在线观看,亚洲а∨天堂久久精品9966,亚洲成a人片在线观看你懂的,亚洲av成人片无码网站,亚洲国产精品无码久久久五月天

Swift3新特性

2018-07-20    來(lái)源:編程學(xué)習(xí)網(wǎng)

容器云強(qiáng)勢(shì)上線!快速搭建集群,上萬(wàn)Linux鏡像隨意使用

Swift3 改變了很多大量的內(nèi)容,如果你的代碼中不作出必要的改變肯定會(huì)被拒絕.如果你認(rèn)為Swift從1.2和2.0的改變的是很大,那是因?yàn)槟氵沒有看到3的改變.

本文中會(huì)盡可能通過代碼來(lái)講解Swift3的重要變化,更新代碼的時(shí)刻已經(jīng)到來(lái)了.

警告# 1:有很多的變化,其中一些看起來(lái)小。然而這些變化是一個(gè)一次性的事件,使語(yǔ)言更好地來(lái),同時(shí)意味著在以后版本的變化是顯著更小。

所有的函數(shù)參數(shù)標(biāo)簽

Swift2.0中的原有的函數(shù)和方法調(diào)用方式發(fā)生了徹底的改變.在Swift2.x及更早版本中,方法名稱不需要設(shè)置第一個(gè)參數(shù)標(biāo)簽,現(xiàn)在調(diào)用方式必須顯示顯示設(shè)置第一個(gè)參數(shù)的標(biāo)簽,例如:

names.indexOf("Taylor")
        "Taylor".writeToFile("filename", atomically: true, encoding: NSUTF8StringEncoding)
        SKAction.rotateByAngle(CGFloat(M_PI_2), duration: 10)
        UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
        override func numberOfSectionsInTableView(tableView: UITableView) -> Int
        func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
        NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)

Swift3 要求所有的參數(shù)必須要設(shè)置標(biāo)簽,除非特別設(shè)置,通過方法名中的關(guān)于第一個(gè)參數(shù)的說明已經(jīng)取去除.Swift2和Swift3對(duì)比:

names.indexOf("Taylor")
        names.index(of: "Taylor")

        "Taylor".writeToFile("filename", atomically: true, encoding: NSUTF8StringEncoding)
        "Taylor".write(toFile: "somefile", atomically: true, encoding: String.Encoding.utf8)

        SKAction.rotateByAngle(CGFloat(M_PI_2), duration: 10)
        SKAction.rotate(byAngle: CGFloat(M_PI_2), duration: 10)

        UIFont.preferredFontForTextStyle(UIFontTextStyleSubheadline)
        UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline)

        override func numberOfSectionsInTableView(tableView: UITableView) -> Int
        override func numberOfSections(in tableView: UITableView) -> Int

        func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView?
        func viewForZooming(in scrollView: UIScrollView) -> UIView?

        NSTimer.scheduledTimerWithTimeInterval(0.35, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)
        Timer.scheduledTimer(timeInterval: 0.35, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)

回調(diào)中,NSTimer的調(diào)用方式發(fā)生的改變,我們可以在FileManager

, Data, Date, URLRequest, UUID,NotificationCenter, 同樣的我們會(huì)發(fā)現(xiàn)一些基礎(chǔ)數(shù)據(jù)類型去除了“NS”前綴~

關(guān)于第一個(gè)標(biāo)簽的設(shè)置會(huì)導(dǎo)致一些連鎖反應(yīng),當(dāng)使用其他的框架如UIKit,他們期待原有的 "no first parameter name"規(guī)則在Swift 3.

這些是在Swift 2.2的簽名:

override func viewWillAppear(animated: Bool)
        override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
        override func didMoveToView(view: SKView)
        override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?)
        func textFieldShouldReturn(textField: UITextField) -> Bool

Swift3中,第一個(gè)參數(shù)標(biāo)簽,通過下劃線來(lái)設(shè)置,如下:

override func viewWillAppear(_ animated: Bool)
        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
        override func didMoveToView(_ view: SKView)
        override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
        func textFieldShouldReturn(_ textField: UITextField) -> Bool

省略不必要的字符

當(dāng)Swift在2015年12月開放源代碼的時(shí)候,新的API標(biāo)準(zhǔn)包含三個(gè)決定性的話:“省略不必要的字。其中的變化,會(huì)使代碼調(diào)用更加簡(jiǎn)潔.

Swift 2.2 例子:

let blue = UIColor.blueColor()
        let min = numbers.minElement()
        attributedString.appendAttributedString(anotherString)
        names.insert("Jane", atIndex: 0)
        UIDevice.currentDevice()

你能辨認(rèn)出不必要的字符嗎?當(dāng)使用UIColor定義藍(lán)色blue是必要的,blueColor是不必要的,Swift3中上面的代碼:

let blue = UIColor.blue
        let min = numbers.min()
        attributedString.append(anotherString)
        names.insert("Jane", at: 0)
        UIDevice.current

對(duì)比之下,代碼較之前更精簡(jiǎn).

Swift2.2 和 Swift3 代碼中字符串對(duì)比如下:

"  Hello  ".stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
        "  Hello  ".trimmingCharacters(in: .whitespacesAndNewlines)

        "Taylor".containsString("ayl")
        "Taylor".contains("ayl")

        "1,2,3,4,5".componentsSeparatedByString(",")
        "1,2,3,4,5".components(separatedBy: ",")

        myPath.stringByAppendingPathComponent("file.txt")
        myPath.appendingPathComponent("file.txt")

        "Hello, world".stringByReplacingOccurrencesOfString("Hello", withString: "Goodbye")
        "Hello, world".replacingOccurrences(of: "Hello", with: "Goodbye")

        "Hello, world".substringFromIndex(7)
        "Hello, world".substring(from: 7)

        "Hello, world".capitalizedString
        "Hello, world".capitalized

警告:capitalized始終是一個(gè)屬性,但是lowercaseString和uppercaseString已經(jīng)被轉(zhuǎn)換成lowercased()和uppercased()替換.

關(guān)于Swift的變化有很多,以上的對(duì)比并不是變化最大的,有些地方變化不是特別明顯:

dismiss(animated: true, completion: nil)

第一眼看到dismiss時(shí)候,是不是想到 "dismiss what?" Swift 2.2中代碼如下:

dismissViewControllerAnimated(true, completion: nil)

現(xiàn)在甚至是complete都是可選參數(shù):

dismiss(animated: true)

同樣的改變發(fā)生在 prepareForSegue() 方法中,現(xiàn)在如下:

override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?)

枚舉和屬性中的大小字母替換成小寫字母

我們?cè)谑褂妙惡徒Y(jié)構(gòu)體,枚舉一直遵守著參數(shù)名稱以大寫字母開頭,雖然大寫字母與參數(shù)無(wú)關(guān),Swift3中開始使用小寫字母.Swift 2.2創(chuàng)建 NSURLRequest對(duì)象使用 NSURLRequest(URL: someURL) ,注意大寫字母"URL". Swift 3重寫 URLRequest(url: someURL) ,同時(shí)意味著將使用 webView.request?.url?.absoluteString 來(lái)讀取webview的返回參數(shù).

當(dāng)屬性的名稱的一部分是大寫的時(shí)候就不是那么和諧,例如 cgcolor 或 cicolor ,Swift3中的調(diào)用方式如下:

let red = UIColor.red.cgColor

這種變化有利于驅(qū)動(dòng)一致性,所有的屬性和參數(shù)都應(yīng)該以小寫字母開頭,也沒有例外.

枚舉同樣在發(fā)生變化,從大寫改變?yōu)樾,枚舉是一個(gè)數(shù)據(jù)類型,意味著無(wú)論你使用的任何蘋果的枚舉都將小寫:

UIInterfaceOrientationMask.Portrait // old
        UIInterfaceOrientationMask.portrait // new

        NSTextAlignment.Left // old
        NSTextAlignment.left // new

        SKBlendMode.Replace // old
        SKBlendMode.replace // new

這種微小的改變涉及到了可選數(shù)據(jù)類型,原有的可選類型在枚舉中:

enum Optional { case None case Some(Wrapped)}

如果項(xiàng)目中原有用到了Some,需要切換到度對(duì)應(yīng)的some,當(dāng)然也可以通過不使用some,以下代碼供參考:

for case let .some(datum) in data {
            print(datum)
        }
        for case let datum? in data {
            print(datum)
        }`

Swift形式的C函數(shù)導(dǎo)入

Swift3中介紹了C函數(shù)的屬性,允許開發(fā)者通過新的和簡(jiǎn)潔的方式導(dǎo)入C函數(shù).例如,從“CGContext”映射屬性的方式至一個(gè)CGContext對(duì)象.是的,這意味著原來(lái)類似CGContextSetFillColorWithColor()這種可怕的方法被移除.

為了證明這一點(diǎn),以下是Swift2.2中的例子:

let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
        CGContextSetFillColorWithColor(ctx, UIColor.redColor().CGColor)
        CGContextSetStrokeColorWithColor(ctx, UIColor.blackColor().CGColor)
        CGContextSetLineWidth(ctx, 10)
        CGContextAddRect(ctx, rectangle)
        CGContextDrawPath(ctx, .FillStroke)

        UIGraphicsEndImageContext()

在Swift3中CGContex可以被視作一個(gè)對(duì)象,你可以調(diào)用方式,而不是重復(fù)的使用CGContext,所有代碼重寫如下:

if let ctx = UIGraphicsGetCurrentContext() {
            let rectangle = CGRect(x: 0, y: 0, width: 512, height: 512)
            ctx.setFillColor(UIColor.red.cgColor)
            ctx.setStrokeColor(UIColor.black.cgColor)
            ctx.setLineWidth(10)
            ctx.addRect(rectangle)
            ctx.drawPath(using: .fillStroke)

            UIGraphicsEndImageContext()
        }

提示:在Swift2.2和Swift3.0中 UIGraphicsGetCurrentContext() 返回了可空的CGContext,但是因?yàn)镾wift3中方式的形式調(diào)用所以使用之前需要判空.

C函數(shù)的映射無(wú)處不在,比如說 CGPDFDocument 的 numberOfPages 屬性, CGAffineTransform 如果寫起來(lái)也是非常驚人的,以下是一些新老代碼對(duì)比:

CGAffineTransformIdentity
        CGAffineTransform.identity

        CGAffineTransformMakeScale(2, 2)
        CGAffineTransform(scaleX: 2, y: 2)

        CGAffineTransformMakeTranslation(128, 128)
        CGAffineTransform(translationX: 128, y: 128)

        CGAffineTransformMakeRotation(CGFloat(M_PI))
        CGAffineTransform(rotationAngle: CGFloat(M_PI))

動(dòng)詞和名詞

Swift3中的動(dòng)詞和名詞讓人比較坤混,下面是比較重要的Swift3 API指南,讀取來(lái)有點(diǎn)繞:

  • "When the operation is naturally described by a verb, use the verb’s imperative for the mutating method and apply the “ed” or “ing” suffix to name its nonmutating counterpart"

  • "Prefer to name the nonmutating variant using the verb’s past participle"

  • "When adding “ed” is not grammatical because the verb has a direct object, name the nonmutating variant using the verb’s present participle"
  • "When the operation is naturally des

Swift3相當(dāng)于給我們上了一堂英語(yǔ)語(yǔ)法課,方法的改變很微妙,有時(shí)候會(huì)讓人感到困惑.看一些簡(jiǎn)單的代碼:

myArray.enumerate()
        myArray.enumerated()

        myArray.reverse()
        myArray.reversed()

Swift3中在每個(gè)方法的最后都加入一個(gè)“d”,返回一個(gè)值.

當(dāng)涉及到數(shù)組排序的時(shí)候這些規(guī)則有時(shí)候會(huì)導(dǎo)致混亂。Swift2.2中用sort()返回排序后的數(shù)組,并sortinplace()到位數(shù)組排序。Swift3,sort()更名sorted()(上述例子),和sortinplace()更名sort()。

Swift3的這些變化很容易閱讀,其中一些是微小的,但是會(huì)引入大量的破壞,蘋果讓工程師的生活更加的建安,同時(shí)也會(huì)促進(jìn)工程師的技能提升.

 

 

來(lái)自:http://www.jianshu.com/p/b6abe5979e80

標(biāo)簽: idc 代碼 開發(fā)者

版權(quán)申明:本站文章部分自網(wǎng)絡(luò),如有侵權(quán),請(qǐng)聯(lián)系:west999com@outlook.com
特別注意:本站所有轉(zhuǎn)載文章言論不代表本站觀點(diǎn)!
本站所提供的圖片等素材,版權(quán)歸原作者所有,如需使用,請(qǐng)與原作者聯(lián)系。

上一篇:iOS指紋識(shí)別登錄流程及實(shí)現(xiàn)

下一篇:Android中的緩存