0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift] KeyPath

Last updated at Posted at 2020-06-14

Swift5 のKeyPath キーワードについて勉強しましたので、メモします。

#KeyPathの定義
KeyPathの公式ドキュメントですが、理解できない。。。
https://developer.apple.com/documentation/swift/swift_standard_library/key-path_expressions

下記のリンクを参照しました。

https://qiita.com/BlueEventHorizon/items/dee0eb27fbba83ed8ea9

コード

1.struct

StudentModel.swift
struct StudentModel {
    var studentId = "0"
    var name = "new"
    var age = "0"
}

2. keyPath確認

sample.swift(type)

public func confirmKeyPathType() {
   var studentModel = StudentModel()
   //keyPath 設定
   let nameKeyPath = \StudentModel.name
        
   print(" \(#function) keyPath type: \(String(describing: type(of: nameKeyPath)))")
}

上記の結果ログは下記の通り__WritableKeyPath__です。


confirmKeyPathType() keyPath type: WritableKeyPath

理由は下記の通りの属性のため

・KeyPath : ReadOnly
・WritableKeyPath : Read&Update

3. KeyPath 値更新

sample.swift(update)
   var studentModel = StudentModel()
   let nameKeyPath = \StudentModel.name
   //keyPath 値更新
   studentModel[keyPath: nameKeyPath ] = "updated"

4. Sort

sample.swift(array)
        
   let array =  [StudentModel(studentId: "003", name: "3", age: "10"),
   StudentModel(studentId: "002", name: "1", age: "15"),
   StudentModel(studentId: "001", name: "2", age: "20")]

KeyPathを利用し、ソート

sample.swift(Sort2)
        
   let ageKeyPath = \StudentModel.age
   let results = array.sorted {
            $0[keyPath: ageKeyPath] > $1[keyPath: ageKeyPath]
   }
   print(" \(#function) 2.sorted result: \(results) ")

一般的なソート

sample.swift(Sort)
        
   let results = array.sorted{ $0.age > $1.age } 
   print(" \(#function) 2.sorted result: \(results) ")

Github

https://github.com/mario7/studyForiOS/blob/realmJsonSample/realmAndJsonSample/message/SampleStudentModel.swift

おまけ

Sort と Sorted 差

ソートされたリストが返却される。
sorted-help.png

対象リストがソートされるため、返却値なし。
sort-help.png

KVO

kvo.png

observeがあれば、ごんな感じですかな? 
ごめんなさい。次回調査します。

sample.swift(kvo)
    let webview = UIWebView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    webview.observe(\UIWebView.pageLength, options: .new) {_,_ in
            //handler
        }

以上です。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?