突然兴起复习一下Swift3.0

/// 参考Swift3.0.1文档
/// 摘录来自: Apple Inc. “The Swift Programming Language (Swift 3.0.1)”。 iBooks.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        aSwiftTour()

    }

    func aSwiftTour(){
        //Swift中的输出语句
        print("Hello World")

        //MARK: - 变量
        /**var声明变量
         Swift具备自动推导的能力
         右边是什么类型这个变量或者是常量就自动的是什么类型了
        */
        var variable = 66
        variable = 88
        //MARK: - let声明常量
        let constant = 66
        print(variable,constant)

        //指定变量的类型 隐式指定
        let implictInteger = 66     //Int
        let implicitDouble = 66.0   //Double

        //显式地指定类型为Double
        let explicitDouble: Double = 88 //Double
        print(implictInteger,implicitDouble,explicitDouble)

        let label = "The width is"
        let width = 94
        let widthLabel = label + String(width)
        print(widthLabel)

        //MARK: - 数字和字符串的拼接
        let apples = 3
        let oranges = 5
        let appleSummary = "I have \(apples) apples."
        let fruitSummary = "I have \(apples + oranges) pieces of fruit."

        //MARK: - 数组操作
        var shoppingList = ["catfish", "water", "tulips", "blue paint"]
        shoppingList[1] = "bottle of water"

        //MARK: - 字典操作 key:value
        var occupations = [
            "Malcolm": "Captain",
            "Kaylee": "Mechanic",
            ]
        occupations["Jayne"] = "Public Relations"

        //创建空数组和空字典的方式
        //创建一个元素类型为字符串的数组
        let emptyArray = [String]()
        //key为String类型value为Float类型的字典
        let emptyDictionary = [String: Float]()

        //MARK: - 数组字典更简单的方式
        /**
         “If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.”
         摘录来自: Apple Inc. “The Swift Programming Language (Swift 3.0.1)”。 iBooks.
         */
        shoppingList = []//默认是[String]
        occupations = [:]//默认是[String:String]

         //MARK: - 控制流
        //注意for if else 的格式
        let individualScores = [75, 43, 103, 87, 12]
        var teamScore = 0
        for score in individualScores {
            if score > 50 {
                teamScore += 3
            } else {
                teamScore += 1
            }
        }
        print(teamScore)

         //MARK: - ?是可选值类型
        var optionalString: String? = "Hello"
        print(optionalString == nil)

        var optionalName: String? = "John Appleseed"

        var greeting = "Hello!"
        if let name = optionalName {
            greeting = "Hello, \(name)"

        }

        //MARK: - “Another way to handle optional values is to provide a default value ”“using the ?? operator. If the optional value is missing, the default value is used instead.”

        let nickName: String? = nil
        let fullName: String = "John Appleseed"
        let informalGreeting = "Hi \(nickName ?? fullName)"

        /**
         (lldb) po nickName
         nil

         (lldb) po fullName
         "John Appleseed"

         (lldb) po informalGreeting
         "Hi John Appleseed"
         */

         //MARK: - Switch Case的用法
        let vegetable = "red pepper"
        switch vegetable {
        case "celery":
            print("Add some raisins and make ants on a log.")
        case "cucumber", "watercress":
            print("That would make a good tea sandwich.")

            //用x来标识vegetable 看看这个字符串的尾部是否有pepper   Returns a Boolean value indicating whether the string ends with the specified suffix.
        case let x where x.hasSuffix("pepper"):
            print("Is it a spicy \(x)?")
            //Is it a spicy red pepper?

        default:
            print("Everything tastes good in soup.")

        }

         //MARK: - 快速遍历数组 并且找出来最大值
        /**
         三个字典还是鄙视比较好玩的 素数 斐波那契数列 平方
         */
        let interestingNumbers = [
            "Prime": [2, 3, 5, 7, 11, 13],
            "Fibonacci": [1, 1, 2, 3, 5, 8],
            "Square": [1, 4, 9, 16, 25],
            ]
        var largest = 0
        for (kind, numbers) in interestingNumbers {
            for number in numbers {
                if number > largest {
                    largest = number
                }
            }
        }
        print(largest)  //25

        //MARK: - 循环
        var n = 2
        while n < 100 {
            n = n * 2
        }
        print(n)
        //128
        var m = 2
        //就类似于do while
        repeat {
            m = m * 2
        } while m < 100
        print(m)

        //128

        /**

        “Use ..< to make a range that omits its upper value, and use ... to make a range that includes both values.”
         */

        var total = 0
        for i in 0..<4 {
            total += i //1 2 3
        }

        print(total)//6

        var totalBoth = 0
        for i in 0...4 {
            totalBoth += i//1 2 3 4
        }
        print(totalBoth)//10

         //MARK: - 函数和闭包
        //函数            函数参数                    返回值
        func greet(person: String, day: String) -> String {
            return "Hello \(person), today is \(day)."
        }
        let s = greet(person: "Bob", day: "Tuesday")

        //"Hello Bob, today is Tuesday."

        func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
            var min = scores[0]
            var max = scores[0]
            var sum = 0

            for score in scores {
                if score > max {
                    max = score
                } else if score < min {
                    min = score
                }
                sum += score
            }

            return (min, max, sum)
        }
        let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
        print(statistics.sum)
        print(statistics.2)
        //120  120
        /**
         (lldb) po statistics.min
         3

         (lldb) po statistics.max
         100

         (lldb) po statistics.sum
         120
         */

         //可变参数的函数 zhu‘yi
        func sumOf(numbers: Int...) -> Int {
            var sum = 0
            for number in numbers {
                sum += number
            }
            return sum
        }
        let sumOfEmptyParam = sumOf()

        let sumOfThree = sumOf(numbers: 42, 597, 12)

        /**
         (lldb) po sumOfEmptyParam
         0

         (lldb) po sumOfThree
         651
         */

        //函数A的内部有函数B 函数A内部还调用了函数B
        func returnFifteen() -> Int {
            var y = 10
            func add() {
                y += 5
            }
            add()
            return y
        }

        let fifteenFunc = returnFifteen()   //15

        //参数为空 返回值为闭包类型
        func makeIncrementer() -> ((Int) -> Int) {
            //参数为整型  返回值为整数
            func addOne(number: Int) -> Int {
                return 1 + number
            }
            return addOne
        }
        var increment = makeIncrementer()
        increment(7) //8

        //“A function can take another function as one of its arguments.
        //函数的返回值是一个函数 而且不仅仅是一个函数那么简单 只可意会哈哈
        func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
            for item in list {
                if condition(item) {
                    return true

                }
            }
            return false
        }
        func lessThanTen(number: Int) -> Bool {
            return number < 10
        }
        var numbers = [20, 19, 7, 12]
        let nubersB = hasAnyMatches(list: numbers, condition: lessThanTen)

        //true 7满足条件
        print(nubersB)

         //MARK: - 闭包
        //“You can write a closure without a name by surrounding code with braces ({}). ”
        //到了闭包了 先停一下??

        numbers.map({
            (number: Int) -> Int in
            let result = 3 * number
            return result
            })

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }

}
时间: 2024-08-04 17:01:43

突然兴起复习一下Swift3.0的相关文章

(细节控)swift3.0与融云IMKIT开发问题(一部分) override func onSelectedTableRow Method does not override any method from its superclass

原官网文档方案如下,在swift3.0的情况下出现 override func onSelectedTableRow  Method does not override any method from its superclass 这是因为swift3.0 有很多变更,需要更换下onSelectedTableRow参数. //重写RCConversationListViewController的onSelectedTableRow事件 override func onSelectedTableR

Swift2.3 --&gt; Swift3.0 的变化

Swift3.0语法变化 首先和大家分享一下学习新语法的技巧: 用Xcode8打开自己的Swift2.3的项目,选择Edit->Convert->To Current Swift Syntax- 让Xcode帮我们把Swift2.3的代码转换为Swift3.0. 手动调出Xcode自动转换Swift2.3 到 Swift3.0 弹出语言版本选择界面,选择Covert to Swift3,Next:  进入选择模块界面: 选择模块界面 建议只选择自己创建的模块,第三方框架的模块最好不要使用Xco

使用 swift3.0高仿新浪微博

项目地址:https://github.com/SummerHH/swift3.0WeBo 使用 swift3.0 高仿微博,目前以实现的功能有,添加访客视图,用户信息授权,首页数据展示(支持正文中连接匹配,@匹配)支持照片浏览,大图浏览,保存图片到相册本地, 实现发布微博,发微博添加照片,发送Emoticon表情等功能, 先看下项目整体框架 项目使用 MVC 框架,但是在写的过程中也用到了 MVVM设计模式

使用的一些支持swift3.0的开源库

#解决键盘弹起遮挡工具 pod 'IQKeyboardManagerSwift', '~>4.0.6' #多种类型弹出框 pod 'SCLAlertView', :git => 'https://github.com/vikmeup/SCLAlertView-Swift' # Alamofire 网络库 (4.1.0最低支持iOS8.0,4.0最低支持iOS9.0) pod 'Alamofire', '~> 4.0' # swift解析json库 pod 'SwiftyJSON', :g

Swift3.0 函数闭包与OC Block

刚接触Swift,如有不对的点,欢迎指正.转载请说明出处 Swift中定义一个基本函数 //定义一个函数,接收一个字符串,返回一个String类型的值 func test(name:String) -> String { return ("输出了\(name)") } //通用形式 func name(parameters) -> return type { function body } Swift 中基本的闭包函数与OC中Block的相似点 带参闭包 //OC中Bloc

swift3.0:CoreData的使用

一.介绍 CoreData不像slqite3那样编写代码繁琐,同时避免了使用了SQL语句的麻烦,也可以回避使用C语言的语法,降低了iOS开发的技术门槛. CoreData可降低开发成本,提高代码质量.它是一个完全面向对象的API,能够合理管理内存,负责在数据库中存储数据,底层也是由类似 于SQL的技术实现的.CoreData是持久化存储的最佳方式,数据最终的存储类型可以是SQLite数据库.XML.二进制.内存或自定义数据类型 它和SQLite的区别是:只能取出整个实体记录,然后分离,之后才能得

swift3.0 coredata 的使用

//swift3.0在语法上有很大的改变,以简单的增删改查为例,如下: //User类如下: import Foundation import CoreData extension User { @nonobjc public class func fetchRequest() -> NSFetchRequest<User> { return NSFetchRequest<User>(entityName: "User"); } @NSManaged pu

iOS 日期处理 (Swift3.0 NSDate)

处理日期的常见情景 NSDate -> String & String -> NSDate 日期比较 日期计算(基于参考日期 +/- 一定时间) 计算日期间的差异 拆解NSDate对象(分解成year/month/day/hour/minute/second 等) NSDate相关类 NSDate DateFormatter DateComponents DateComponentFormatter Calendar Date structure: Swift3.0中引入了Date s

swift3.0变化总结

Swift 3.0 做出的改变很大,在这篇文章中,我将尽我所能,利用代码样例给大家解释Swift 3.0最重要(要命)的改变,希望大家能够做好升级Swift 3.0 的准备.Swift 3.0的改变不仅仅是我下面的这个列表,但是列表中的每一项都是对你的一个巨大的打击. 虽然Swift 3.0 仍处于开发阶段.Swift 3.0 会有很多很多的变化,其中一些可能会在细微之处.然而,我们希望这些变化是一次性的.为了使Swift可以在未来几年更好的发展,在以后的版本更新中改变应该的显著变小.一些Swi