Swift 5

作者: ienos | 来源:发表于2019-05-06 15:42 被阅读0次

扩展字符串分割符

作用:特殊字符在字符串中没有影响
符号使用: #" exampleString "#

  • eg: #" Line 1 \n Line 2"#
    result: 打印 \n,但是不会换行
    如果需要特殊字符生效,在 \ 后面加 #
  • eg: #" Line 1 \#n Line 2 "#
    result: 换行,使用 # Line 1 \###n Line 2 "#也能达到相同的效果
  • eg:
let threeMoreDoubleQuotationMarks = #"""
Here are three more double quotes: """
"""#

result:Here are three more double quotes: """
原来的效果是 """ 包括的字符串中是多行字符串,然后使用 #""" """# 取消了字符串(Here are three more double quotes: """)中原来的 """ 的效果

dynamicCallable

应用这个属性到 类、结构体、枚举或者协议 对待某个实例的类型作为

  • 必须至少实现 dynamicallyCall(withArguments:)dynamicallyCall(withKeywordArguments:) 其中一个方法
  • 作用:调用一个动态调用类型可调用的类型

dynamicallyCall(withArguments:)

  • 动态设置多成员参数
  • 参数实现协议 ExpressibleByArrayLiteral
@dynamicCallable
struct TelephoneExchange {
    func dynamicallyCall(withArguments phoneNumber: [Int]) {
        if phoneNumber = [4, 1, 1] {
            print("Get Swift help on forums.swift.org")
        } else {
            print("Unrecognized number")
        }
    }
}

// Use a dynamic method call
dial(8, 6, 7, 5, 3, 0, 9)

// Call the underlying method directly
dial.dynamicallyCall(withArguments: [4, 1, 1])

dynamicallyCall(withKeywordArguments:)

@dynamicCallable
struct Repeater {
    func dynamicallyCall(withKeywordArguments pairs: KeyValuePairs<String, Int>) -> String {
        return pairs
                .map { label, count in
                        repeatElement(label, count: count).joined(separator: "")
                }
                .joined(separator: "\n")
   }
}

let repeatLabels = Repeater()
print(repeatLabels(a: 1, b: 2, c: 3, b: 2, a: 1))

  • 单参数遵循 ExpressibleByDictionaryLiteral
  • 能够返回任何类型
  • 调用者能够包括重复的参数标签

Unknown

@unknown修饰 switch 中的 default,编译提示 switch 中没有对应实现的 case

KeyPath 表达式

\type name.path

struct SomeStructure {
    var someValue: Int
}

let s = SomeStructure(someValue: 12)
let pathToProperty = \SomeStructre.someValue

let value = s[keyPath: pathToProperty]

type name 当能够类型推断时可以被省略 .someProperty

class SomeClass: NSObject {
    @objc var someProperty: Int
    init(someProperty: Int) {
        self.someProperty = someProperty
    }
}

let c = SomeClass(someProperty: 10)
c.observe(\.someProperty) { object, change in
    // ...
}

引用 self
\.self

var compoundValue = (a: 1, b: 2)
compoundValue[keyPath: \.self] = (a: 10, b: 20)

引用属性的属性

struct OuterStructure {
    var outer: SomeStructure
    init(someValue: Int) {    
        self.outer = SomeStructure(someValue: someValue)
    }
}

let nested = OuterStructure(someValue: 24)
let nestedKeyPath = \OuterStructure.outer.someValue

let nestedValue = nested[keyPath: nestedKeyPath]

使用下标

let greetings = ["hello", "hola", "bonjour", "greeting"]
let myGreeting = greetings[keyPath: \[String].[1]]

var index = 2
let path = \[String].[index]
let fn: ([String]) -> String = { strings in strings[index] }

print(greetings[keyPath: path])
// Prints "bonjour"
print(fn(greetings))
// Prints "bonjour"

// 重新设置 index 不会影响 path 
index += 1
print(greetings[keyPath: path]) // Prints bonjour

// Because 'fn' closes over 'index', it uses the new value
print(fn(greetings)) // Print greeting

可选绑定和强制解包

let firstGreeting: String? = greetings.first
print(firstGreeting?.count as Any)

// Prints "Optional(5)"

// Do the same things using a key path
let count = greetings[keyPath: \[String].first?.count]
print(count as Any)
// Prints "Optional(5)"

混合

let interestingNumbers = ["prime": [2, 3, 5, 7, 11, 13, 17],
                          "triangualar": [1, 3, 6, 10, 15, 21, 28],
                          "hexagonal": [1, 6, 15, 28, 45, 66, 91]]
print(interestingNumbers[keyPath: \[String: [Int]].["prime"]] as Any)
print(interestingNumbers[keyPath: \[String: [Int]].["prime"]![0]])
print(interestingNumbers[keyPath: \[String: [Int]].["hexagonal"]!.count])
print(interestingNumbers[keyPath: \[String: [Int]].["hexagonal"]!.count.bitWidth])

相关文章

网友评论

    本文标题:Swift 5

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