Swift4 -- 新特性

作者: 奇董 | 来源:发表于2017-12-28 16:26 被阅读25次

1. 单边 ranges

//ranges
let nums = ["1","2","3"]
//swift3
nums[0...2]
//swift4
nums[0...]

无限序列

var a = 1...
print(a.contains(100000))

这里的a 的类型 CountablePartialRangeForm 遵循 RangeExpression 协议

模式匹配

配合 switch

func descNums(_ num: Int) -> String {
    switch num  {
    case ..<10:
        return "一位数字"
    default:
        return "多位数"
    }
}

descNums(9)

2. Strings

现在String 是集合类型 实现了集合的方法

let string = "1234"
string.count
string.isEmpty

for item in string {
    print(item)
}

String的子字符串的类型现在必须为String.index 或者Range<String.index> 以前可以为Int

string[string.startIndex..<string.endIndex]
string.prefix(3)
string.prefix(upTo: string.endIndex)

let b = string[string.startIndex..<string.endIndex]
type(of: b) // Substring.type

let c = String(b)
type(of: c) // String.type

截取的substring 指向的是原版本string的那块内存

unicode

let d: Character = "😝"
type(of: d) //Character


let d1 = "😝"
type(of: d1) //String

Range<String.Index> 和 NSRange 转换

NSRegularExpression, NSAttributedString, NSLinguisticTagger api 需要NSRange

Foundation 提供新的初始化方法

// Rnage -> NSRange
let aa = "a124😝"
let range = NSRange(aa.startIndex..., in: aa) //region Range<String.index>

aa.utf16.count // 6
aa.count // 5

这里NSRange 是 已utf-16 计数

//NSRange -> Range
let text = "You have traveled 483.2 miles."
let pattern = "[0-9]+(\\.([0-9])?)?"

let regex = try! NSRegularExpression(pattern: pattern, options: [])

let nsrange = NSRange(text.startIndex..., in: text)

let mile = regex.rangeOfFirstMatch(in: text, options: [], range: nsrange)

let range1 = Range(mile, in: text)

print(range1)

text[range1!] //483.2

多行字符串

let multiString = """
AAA
bbb
ccc
"""

3 字典增强功能

基于序列初始化字典
let array = ["1","2","3"]

//[1:"1",2:"2",3:"3"]
let dic = Dictionary.init(uniqueKeysWithValues: zip(1..., array))

let tupleArray = [(1,"1"),(2,"2")]
let dic2 = Dictionary.init(uniqueKeysWithValues: tupleArray)

合并

当转化字典的时候可能遇到key 冲突
可以确定第一个 或者 最后一个 解决冲突

let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]

     let firstValues = Dictionary(pairsWithDuplicateKeys,
                                  uniquingKeysWith: { (first, _) in first })
     // ["b": 2, "a": 1]

     let lastValues = Dictionary(pairsWithDuplicateKeys,
                                 uniquingKeysWith: { (_, last) in last })
     // ["b": 4, "a": 3]
let defaultStyling: [String: UIColor] = [
    "body": .black, "title": .blue, "byline": .green
]
var userStyling: [String: UIColor] = [
    "body": .purple, "title": .blue
]
userStyling.merge(defaultStyling) { (user, _) -> UIColor in
    user
}
// ["body": .purple, "title": .blue, "byline": .green]

下标值

aa[3] ?? "55" //3
aa[3, default: "55"] //4

数组分组 划分为 字典

let aa = [1,2,3,4,-1]

let dic = Dictionary.init(grouping: aa) { (key) -> String in
    if(key > 0) {
        return "1"
    }else {
        return "-1"
    }
}
//["1": [1, 2, 3, 4], "-1": [-1]]

4 @objc 和 @nonobjc

在swift 4 重写 和 继承 都会
继承@objc 标识符

class Super {
  @objc func foo() {}
}

class Sub: Super {
  // inferred @objc
  override func foo() {}
}

@objc protocol MyDelegate {
  func bar()
}

class MyThirdClass: MyDelegate {
  // inferred @objc
  func bar() {}
}

其他

extension 中的privite

以前声明privite 为私有属性 当extension扩展需要私有属性的时候
用fileprivite声明

swift4 privite 默认同文件中 extension 也可以获取到私有属性

swapAt

var numbers = Array(1...5)
//swap(&numbers[1], &numbers[3]) // Illegal in Swift 4
numbers.swapAt(1, 3)
// [1, 4, 3, 2, 5]

swift4 可以指定对象遵循特定的类型和属性

protocol MySpecialDelegateProtocol {}
class MySpecialView: UIView {}
class MyController {
  var delegate: (UIView & MySpecialDelegateProtocol)?

}

简化

public typealias Codable = Decodable & Encodable

迁移swift4

选择
Edit\Convert\To Current Swift Syntax...
因为swift3的@objc 推断模式和 4 不一样
这里需要选择


image.png

选择推荐的方式
最后


image.png

相关文章

  • Swift4新特性

    新特性列表1 序列化与反序列化2 String的多行存储3 key-value Coding的优化4 Range单...

  • swift4新特性

    1. extension 里面可以直接访问 private 修饰的成员属性 2. 聚合协议类型? 新的keypat...

  • Swift4 -- 新特性

    1. 单边 ranges 无限序列 这里的a 的类型 CountablePartialRangeForm 遵循 R...

  • Swift4新特性初探

    写在前面 Swift这门语言已经被越来越多的coders接受,大势所趋,尤其作为一个iOS开发者,更需要进行掌握!...

  • 本周工作总结

    这周发布裤兜语文学生端任务阅读模块的测试版本,解决测试出来的问题,修改部分细节UI。研究swift4新特性,调研新...

  • Swift-Codable协议

    Swift4新特性中,Codable协议真的能狂吸一波粉,个人不太喜欢SwiftyJSON这类的第三方库来解析数据...

  • swift4 特性

  • Swift4 新特性一览

    本篇为 2017 WWDC Session 402 笔记,原视频在这里 语法特性 Swift3中,如果将主体函数的...

  • swift4-字典转模型的一些总结

    使用swift4提供的新特性Codable来实现字典转模型 写在前面,使用过程中要知道的几个小知识点 tip1:如...

  • Swift 4中的新特性(Whatʼs New in Swift

    最近重点看了一些关于Swift4及iOS11新特性的资料,所以准备做一些总结及笔记,内容主要来自前一阵买的iOS ...

网友评论

    本文标题:Swift4 -- 新特性

    本文链接:https://www.haomeiwen.com/subject/scumgxtx.html