我需要以树状方式互连的通用对象的表示。这棵树及其对象应具有以下特征:
Codable 协议(protocol)来编码
作为这个问题末尾的一个例子,我创建了一个满足所有要求但只有一个要求的 Playground : 从 JSON 解码树
一棵树由节点组成,在本例中为 TreePartNode s,它们正在实现 TreePartNodeBase 协议(protocol)。
这个例子中的树是一个 AnyTreePartNode 的数组,它们也实现了 TreePartNodeBase 协议(protocol)并包装了一个实现 TreePartNodeBase 协议(protocol)的对象,它应该是一个通用的 TreePartNode ( TreePartNode<Trunk> , TreePartNode<Branch> 或 TreePartNode<Apple> )。
TreePartNode 具有 treePart 类型的属性 AnyTreePart 。 AnyTreePart(类似于 AnyTreePartNode )包装了一个实现 TreePart 协议(protocol)( Trunk 、 Branch 或 Apple )的对象。
所有这些类都实现了 Codable 和 Equatable 。
import Foundation
///////////// TreePart -> implemented by Trunk, Branch, Apple and AnyTreePart
protocol TreePart: Codable {
var name: String { get set }
func isEqualTo( _ other: TreePart ) -> Bool
func asEquatable() -> AnyTreePart
}
extension TreePart where Self: Equatable {
func isEqualTo( _ other: TreePart ) -> Bool {
guard let otherTreePart = other as? Self else { return false }
return self == otherTreePart
}
func asEquatable() -> AnyTreePart {
return AnyTreePart( self )
}
}
///////////// AnyTreePart -> wrapper for Trunk, Branch and Apple
class AnyTreePart: TreePart, Codable {
var wrappedTreePart: TreePart
var name: String {
get {
return self.wrappedTreePart.name
}
set {
self.wrappedTreePart.name = newValue
}
}
init( _ treePart: TreePart ) {
self.wrappedTreePart = treePart
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case trunk,
branch,
apple
}
required convenience init( from decoder: Decoder ) throws {
let container = try decoder.container( keyedBy: CodingKeys.self )
var treePart: TreePart?
if let trunk = try container.decodeIfPresent( Trunk.self, forKey: .trunk ) {
treePart = trunk
}
if let branch = try container.decodeIfPresent( Branch.self, forKey: .branch ) {
treePart = branch
}
if let apple = try container.decodeIfPresent( Apple.self, forKey: .apple ) {
treePart = apple
}
guard let foundTreePart = treePart else {
let context = DecodingError.Context( codingPath: [CodingKeys.trunk, CodingKeys.branch, CodingKeys.apple], debugDescription: "Could not find the treePart key" )
throw DecodingError.keyNotFound( CodingKeys.trunk, context )
}
self.init( foundTreePart )
}
func encode( to encoder: Encoder ) throws {
var container = encoder.container( keyedBy: CodingKeys.self )
switch self.wrappedTreePart {
case let trunk as Trunk:
try container.encode( trunk, forKey: .trunk )
case let branch as Branch:
try container.encode( branch, forKey: .branch )
case let apple as Apple:
try container.encode( apple, forKey: .apple )
default:
fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePart ) )" )
}
}
}
extension AnyTreePart: Equatable {
static func ==( lhs: AnyTreePart, rhs: AnyTreePart ) -> Bool {
return lhs.wrappedTreePart.isEqualTo( rhs.wrappedTreePart )
}
}
///////////// TreePartNodeBase -> implemented by TreePartNode<T: TreePart> and AnyTreePartNode
protocol TreePartNodeBase: class {
var treePart: AnyTreePart { get set }
var uuid: UUID { get }
var parent: AnyTreePartNode? { get set }
var weakChildren: NSPointerArray { get }
func isEqualTo( _ other: TreePartNodeBase ) -> Bool
func asEquatable() -> AnyTreePartNode
}
extension TreePartNodeBase where Self: Equatable {
func isEqualTo( _ other: TreePartNodeBase ) -> Bool {
guard let otherTreePartNode = other as? Self else { return false }
return self == otherTreePartNode &&
self.treePart == other.treePart &&
self.uuid == other.uuid &&
self.parent == other.parent &&
self.children == other.children
}
func asEquatable() -> AnyTreePartNode {
return AnyTreePartNode( self )
}
}
extension TreePartNodeBase {
var children: [AnyTreePartNode] {
guard let allNodes = self.weakChildren.allObjects as? [AnyTreePartNode] else {
fatalError( "The children nodes are not of type \( type( of: AnyTreePartNode.self ) )" )
}
return allNodes
}
}
///////////// AnyTreePartNode -> wrapper of TreePartNode<T: TreePart>
class AnyTreePartNode: TreePartNodeBase, Codable {
unowned var wrappedTreePartNode: TreePartNodeBase
var treePart: AnyTreePart {
get {
return self.wrappedTreePartNode.treePart
}
set {
self.wrappedTreePartNode.treePart = newValue
}
}
var uuid: UUID {
return self.wrappedTreePartNode.uuid
}
/// The parent node
weak var parent: AnyTreePartNode? {
get {
return self.wrappedTreePartNode.parent
}
set {
self.wrappedTreePartNode.parent = newValue
}
}
/// The weak references to the children of this node
var weakChildren: NSPointerArray {
return self.wrappedTreePartNode.weakChildren
}
init( _ treePartNode: TreePartNodeBase ) {
self.wrappedTreePartNode = treePartNode
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case trunkNode,
branchNode,
appleNode
}
required convenience init( from decoder: Decoder ) throws {
let container = try decoder.container( keyedBy: CodingKeys.self )
// even if an empty Trunk is created, the decoder crashes
self.init( TreePartNode<Trunk>( Trunk() ) )
// This attempt of decoding possible nodes doesn't work
/*
if let trunkNode: TreePartNode<Trunk> = try container
.decodeIfPresent( TreePartNode<Trunk>.self, forKey: .trunkNode ) {
self.init( trunkNode )
} else if let branchNode: TreePartNode<Branch> = try container
.decodeIfPresent( TreePartNode<Branch>.self, forKey: .branchNode ) {
self.init( branchNode )
} else if let appleNode: TreePartNode<Apple> = try cont«ainer
.decodeIfPresent( TreePartNode<Apple>.self, forKey: .appleNode ) {
self.init( appleNode )
} else {
let context = DecodingError.Context( codingPath: [CodingKeys.trunkNode,
CodingKeys.branchNode,
CodingKeys.appleNode],
debugDescription: "Could not find the treePart node key" )
throw DecodingError.keyNotFound( CodingKeys.trunkNode, context )
}
*/
// TODO recreating the connections between the nodes should happen after all objects are decoded and will be done based on the UUIDs
}
func encode( to encoder: Encoder ) throws {
var container = encoder.container( keyedBy: CodingKeys.self )
switch self.wrappedTreePartNode {
case let trunkNode as TreePartNode<Trunk>:
try container.encode( trunkNode, forKey: .trunkNode )
case let branchNode as TreePartNode<Branch>:
try container.encode( branchNode, forKey: .branchNode )
case let appleNode as TreePartNode<Apple>:
try container.encode( appleNode, forKey: .appleNode )
default:
fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePartNode ) )" )
}
}
}
extension AnyTreePartNode: Equatable {
static func ==( lhs: AnyTreePartNode, rhs: AnyTreePartNode ) -> Bool {
return lhs.wrappedTreePartNode.isEqualTo( rhs.wrappedTreePartNode )
}
}
// enables printing of the wrapped tree part and its child elements
extension AnyTreePartNode: CustomStringConvertible {
var description: String {
var text = "\( type( of: self.wrappedTreePartNode.treePart.wrappedTreePart ))"
if !self.children.isEmpty {
text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
}
return text
}
}
///////////// TreeParts (Trunk, Branch and Apple)
class Trunk: TreePart, Codable, Equatable {
var name: String
var color: String
init( name: String = "trunk",
color: String = "#CCC" ) {
self.name = name
self.color = color
}
static func ==(lhs: Trunk, rhs: Trunk) -> Bool {
return lhs.name == rhs.name &&
lhs.color == rhs.color
}
}
class Branch: TreePart, Codable, Equatable {
var name: String
var length: Int
init( name: String = "branch",
length: Int = 4 ) {
self.name = name
self.length = length
}
static func ==(lhs: Branch, rhs: Branch) -> Bool {
return lhs.name == rhs.name &&
lhs.length == rhs.length
}
}
class Apple: TreePart, Codable, Equatable {
var name: String
var size: Int
init( name: String = "apple",
size: Int = 2 ) {
self.name = name
self.size = size
}
static func ==(lhs: Apple, rhs: Apple) -> Bool {
return lhs.name == rhs.name &&
lhs.size == rhs.size
}
}
///////////// TreePartNode -> The node in the tree that contains the TreePart
class TreePartNode<T: TreePart>: TreePartNodeBase, Codable {
var equatableSelf: AnyTreePartNode!
var uuid: UUID
var treePart: AnyTreePart
var weakChildren = NSPointerArray.weakObjects()
private var parentUuid : UUID?
private var childrenUuids : [UUID]?
weak var parent: AnyTreePartNode? {
willSet {
if newValue == nil {
// unrelated code
// ... removes the references to this object in the parent node, if it exists
}
}
}
init( _ treePart: AnyTreePart,
uuid: UUID = UUID() ) {
self.treePart = treePart
self.uuid = uuid
self.equatableSelf = self.asEquatable()
}
convenience init( _ treePart: T,
uuid: UUID = UUID() ) {
self.init( treePart.asEquatable(),
uuid: uuid )
}
init( _ treePart: AnyTreePart,
uuid: UUID,
parentUuid: UUID?,
childrenUuids: [UUID]?) {
self.treePart = treePart
self.uuid = uuid
self.parentUuid = parentUuid
self.childrenUuids = childrenUuids
self.equatableSelf = self.asEquatable()
}
private func add( child: AnyTreePartNode ) {
child.parent = self.equatableSelf
self.weakChildren.addObject( child )
}
private func set( parent: AnyTreePartNode ) {
self.parent = parent
parent.weakChildren.addObject( self.equatableSelf )
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case treePart,
uuid,
parent,
children,
parentPort
}
required convenience init( from decoder: Decoder ) throws {
let container = try decoder.container( keyedBy: CodingKeys.self )
// non-optional values
let uuid: UUID = try container.decode( UUID.self, forKey: .uuid )
let treePart: AnyTreePart = try container.decode( AnyTreePart.self, forKey: .treePart )
// optional values
let childrenUuids: [UUID]? = try container.decodeIfPresent( [UUID].self, forKey: .children )
let parentUuid: UUID? = try container.decodeIfPresent( UUID.self, forKey: .parent )
self.init( treePart,
uuid: uuid,
parentUuid: parentUuid,
childrenUuids: childrenUuids)
}
func encode( to encoder: Encoder ) throws {
var container = encoder.container( keyedBy: CodingKeys.self )
// non-optional values
try container.encode( self.treePart, forKey: .treePart )
try container.encode( self.uuid, forKey: .uuid )
// optional values
if !self.children.isEmpty {
try container.encode( self.children.map { $0.uuid }, forKey: .children )
}
try container.encodeIfPresent( self.parent?.uuid, forKey: .parent )
}
}
extension TreePartNode: Equatable {
static func ==( lhs: TreePartNode, rhs: TreePartNode ) -> Bool {
return lhs.treePart == rhs.treePart &&
lhs.parent == rhs.parent &&
lhs.children == rhs.children
}
}
// enables printing of the wrapped tree part and its child elements
extension TreePartNode: CustomStringConvertible {
var description: String {
var text = "\( type( of: self.treePart.wrappedTreePart ))"
if !self.children.isEmpty {
text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
}
return text
}
}
// MARK: functions for adding connections to other TreeParts for each specific TreePart type
extension TreePartNode where T: Trunk {
func add( child branch: TreePartNode<Branch> ) {
self.add( child: branch.equatableSelf )
}
}
extension TreePartNode where T: Branch {
func add( child apple: TreePartNode<Apple> ) {
self.add( child: apple.equatableSelf )
}
func add( child branch: TreePartNode<Branch> ) {
self.add( child: branch.equatableSelf )
}
func set( parent branch: TreePartNode<Branch> ) {
self.set( parent: branch.equatableSelf )
}
func set( parent trunk: TreePartNode<Trunk> ) {
self.set( parent: trunk.equatableSelf )
}
}
extension TreePartNode where T: Apple {
func set( parent branch: TreePartNode<Branch> ) {
self.set( parent: branch.equatableSelf )
}
}
////////////// Helper
extension NSPointerArray {
func addObject( _ object: AnyObject? ) {
guard let strongObject = object else { return }
let pointer = Unmanaged.passUnretained( strongObject ).toOpaque()
self.addPointer( pointer )
}
}
////////////// Test (The actual usage of the implementation above)
let trunk = Trunk()
let branch1 = Branch()
let branch2 = Branch()
let branch3 = Branch()
let apple1 = Apple()
let apple2 = Apple()
let trunkNode = TreePartNode<Trunk>( trunk )
let branchNode1 = TreePartNode<Branch>( branch1 )
let branchNode2 = TreePartNode<Branch>( branch2 )
let branchNode3 = TreePartNode<Branch>( branch3 )
let appleNode1 = TreePartNode<Apple>( apple1 )
let appleNode2 = TreePartNode<Apple>( apple2 )
trunkNode.add( child: branchNode1 )
trunkNode.add( child: branchNode2 )
branchNode2.add( child: branchNode3 )
branchNode1.add( child: appleNode1 )
branchNode3.add( child: appleNode2 )
let tree = [trunkNode.equatableSelf,
branchNode1.equatableSelf,
branchNode2.equatableSelf,
branchNode3.equatableSelf,
appleNode1.equatableSelf,
appleNode2.equatableSelf]
print( "expected result when printing the decoded trunk node: \(trunkNode)" )
let encoder = JSONEncoder()
let decoder = JSONDecoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
// This is how the encoded tree looks like
let jsonTree = """
[
{
"trunkNode" : {
"children" : [
"399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
"60582654-13B9-40D0-8275-3C6649614069"
],
"treePart" : {
"trunk" : {
"color" : "#CCC",
"name" : "trunk"
}
},
"uuid" : "55748AEB-271E-4560-9EE8-F00C670C8896"
}
},
{
"branchNode" : {
"children" : [
"0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
],
"parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
"treePart" : {
"branch" : {
"length" : 4,
"name" : "branch"
}
},
"uuid" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD"
}
},
{
"branchNode" : {
"children" : [
"6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
],
"parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
"treePart" : {
"branch" : {
"length" : 4,
"name" : "branch"
}
},
"uuid" : "60582654-13B9-40D0-8275-3C6649614069"
}
},
{
"branchNode" : {
"children" : [
"9FCCDBF6-27A7-4E21-8681-5F3E63330504"
],
"parent" : "60582654-13B9-40D0-8275-3C6649614069",
"treePart" : {
"branch" : {
"length" : 4,
"name" : "branch"
}
},
"uuid" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
}
},
{
"appleNode" : {
"parent" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
"treePart" : {
"apple" : {
"name" : "apple",
"size" : 2
}
},
"uuid" : "0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
}
},
{
"appleNode" : {
"parent" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7",
"treePart" : {
"apple" : {
"name" : "apple",
"size" : 2
}
},
"uuid" : "9FCCDBF6-27A7-4E21-8681-5F3E63330504"
}
}
]
""".data(using: .utf8)!
do {
print( "begin decoding" )
/* This currently produces an error: Playground execution aborted: error: Execution was interrupted, reason: signal SIGABRT. The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
let decodedTree = try decoder.decode( [AnyTreePartNode].self, from: jsonTree )
print( decodedTree.first( where: { $0.wrappedTreePartNode.treePart.wrappedTreePart is Trunk } )! )
*/
} catch let error {
print( error )
}
AnyTreePartNode 中的解码函数应该如何解码 JSON?我错过了什么?
最佳答案
我只是从 unowned var wrappedTreePartNode: TreePartNodeBase 行中删除 unowned
并编译相同的代码。
结果:
打印解码后的中继节点时的预期结果:Trunk { Branch { Apple }, Branch { Branch { Apple } } } 开始解码 [树干,分支,分支,分支,苹果,苹果]
代码:
//
// ViewController.swift
// TestDrive
//
// Created by Mahipal on 25/04/18.
// Copyright © 2018 Vandana. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
////////////// Test (The actual usage of the implementation above)
let trunk = Trunk()
let branch1 = Branch()
let branch2 = Branch()
let branch3 = Branch()
let apple1 = Apple()
let apple2 = Apple()
let trunkNode = TreePartNode<Trunk>( trunk )
let branchNode1 = TreePartNode<Branch>( branch1 )
let branchNode2 = TreePartNode<Branch>( branch2 )
let branchNode3 = TreePartNode<Branch>( branch3 )
let appleNode1 = TreePartNode<Apple>( apple1 )
let appleNode2 = TreePartNode<Apple>( apple2 )
trunkNode.add( child: branchNode1 )
trunkNode.add( child: branchNode2 )
branchNode2.add( child: branchNode3 )
branchNode1.add( child: appleNode1 )
branchNode3.add( child: appleNode2 )
let tree = [trunkNode.equatableSelf,
branchNode1.equatableSelf,
branchNode2.equatableSelf,
branchNode3.equatableSelf,
appleNode1.equatableSelf,
appleNode2.equatableSelf]
print( "expected result when printing the decoded trunk node: \(trunkNode)" )
let encoder = JSONEncoder()
let decoder = JSONDecoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
// This is how the encoded tree looks like
let jsonTree = """
[
{
"trunkNode" : {
"children" : [
"399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
"60582654-13B9-40D0-8275-3C6649614069"
],
"treePart" : {
"trunk" : {
"color" : "#CCC",
"name" : "trunk"
}
},
"uuid" : "55748AEB-271E-4560-9EE8-F00C670C8896"
}
},
{
"branchNode" : {
"children" : [
"0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
],
"parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
"treePart" : {
"branch" : {
"length" : 4,
"name" : "branch"
}
},
"uuid" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD"
}
},
{
"branchNode" : {
"children" : [
"6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
],
"parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
"treePart" : {
"branch" : {
"length" : 4,
"name" : "branch"
}
},
"uuid" : "60582654-13B9-40D0-8275-3C6649614069"
}
},
{
"branchNode" : {
"children" : [
"9FCCDBF6-27A7-4E21-8681-5F3E63330504"
],
"parent" : "60582654-13B9-40D0-8275-3C6649614069",
"treePart" : {
"branch" : {
"length" : 4,
"name" : "branch"
}
},
"uuid" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
}
},
{
"appleNode" : {
"parent" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
"treePart" : {
"apple" : {
"name" : "apple",
"size" : 2
}
},
"uuid" : "0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
}
},
{
"appleNode" : {
"parent" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7",
"treePart" : {
"apple" : {
"name" : "apple",
"size" : 2
}
},
"uuid" : "9FCCDBF6-27A7-4E21-8681-5F3E63330504"
}
}
]
""".data(using: .utf8)!
do {
print( "begin decoding" )
// This currently produces an error: Playground execution aborted: error: Execution was interrupted, reason: signal SIGABRT. The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
let decodedTree = try decoder.decode( [AnyTreePartNode].self, from: jsonTree )
print( decodedTree )
} catch let error {
print( error )
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import Foundation
///////////// TreePart -> implemented by Trunk, Branch, Apple and AnyTreePart
protocol TreePart: Codable {
var name: String { get set }
func isEqualTo( _ other: TreePart ) -> Bool
func asEquatable() -> AnyTreePart
}
extension TreePart where Self: Equatable {
func isEqualTo( _ other: TreePart ) -> Bool {
guard let otherTreePart = other as? Self else { return false }
return self == otherTreePart
}
func asEquatable() -> AnyTreePart {
return AnyTreePart( self )
}
}
///////////// AnyTreePart -> wrapper for Trunk, Branch and Apple
class AnyTreePart: TreePart, Codable {
var wrappedTreePart: TreePart
var name: String {
get {
return self.wrappedTreePart.name
}
set {
self.wrappedTreePart.name = newValue
}
}
init( _ treePart: TreePart ) {
self.wrappedTreePart = treePart
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case trunk,
branch,
apple
}
required convenience init( from decoder: Decoder ) throws {
let container = try decoder.container( keyedBy: CodingKeys.self )
var treePart: TreePart?
if let trunk = try container.decodeIfPresent( Trunk.self, forKey: .trunk ) {
treePart = trunk
}
if let branch = try container.decodeIfPresent( Branch.self, forKey: .branch ) {
treePart = branch
}
if let apple = try container.decodeIfPresent( Apple.self, forKey: .apple ) {
treePart = apple
}
guard let foundTreePart = treePart else {
let context = DecodingError.Context( codingPath: [CodingKeys.trunk, CodingKeys.branch, CodingKeys.apple], debugDescription: "Could not find the treePart key" )
throw DecodingError.keyNotFound( CodingKeys.trunk, context )
}
self.init( foundTreePart )
}
func encode( to encoder: Encoder ) throws {
var container = encoder.container( keyedBy: CodingKeys.self )
switch self.wrappedTreePart {
case let trunk as Trunk:
try container.encode( trunk, forKey: .trunk )
case let branch as Branch:
try container.encode( branch, forKey: .branch )
case let apple as Apple:
try container.encode( apple, forKey: .apple )
default:
fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePart ) )" )
}
}
}
extension AnyTreePart: Equatable {
static func ==( lhs: AnyTreePart, rhs: AnyTreePart ) -> Bool {
return lhs.wrappedTreePart.isEqualTo( rhs.wrappedTreePart )
}
}
///////////// TreePartNodeBase -> implemented by TreePartNode<T: TreePart> and AnyTreePartNode
protocol TreePartNodeBase: class {
var treePart: AnyTreePart { get set }
var uuid: UUID { get }
var parent: AnyTreePartNode? { get set }
var weakChildren: NSPointerArray { get }
func isEqualTo( _ other: TreePartNodeBase ) -> Bool
func asEquatable() -> AnyTreePartNode
}
extension TreePartNodeBase where Self: Equatable {
func isEqualTo( _ other: TreePartNodeBase ) -> Bool {
guard let otherTreePartNode = other as? Self else { return false }
return self == otherTreePartNode &&
self.treePart == other.treePart &&
self.uuid == other.uuid &&
self.parent == other.parent &&
self.children == other.children
}
func asEquatable() -> AnyTreePartNode {
return AnyTreePartNode( self )
}
}
extension TreePartNodeBase {
var children: [AnyTreePartNode] {
guard let allNodes = self.weakChildren.allObjects as? [AnyTreePartNode] else {
fatalError( "The children nodes are not of type \( type( of: AnyTreePartNode.self ) )" )
}
return allNodes
}
}
///////////// AnyTreePartNode -> wrapper of TreePartNode<T: TreePart>
class AnyTreePartNode: TreePartNodeBase, Codable {
var wrappedTreePartNode: TreePartNodeBase
var treePart: AnyTreePart {
get {
return self.wrappedTreePartNode.treePart
}
set {
self.wrappedTreePartNode.treePart = newValue
}
}
var uuid: UUID {
return self.wrappedTreePartNode.uuid
}
/// The parent node
weak var parent: AnyTreePartNode? {
get {
return self.wrappedTreePartNode.parent
}
set {
self.wrappedTreePartNode.parent = newValue
}
}
/// The weak references to the children of this node
var weakChildren: NSPointerArray {
return self.wrappedTreePartNode.weakChildren
}
init( _ treePartNode: TreePartNodeBase ) {
self.wrappedTreePartNode = treePartNode
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case trunkNode,
branchNode,
appleNode
}
required convenience init( from decoder: Decoder ) throws {
let container = try decoder.container( keyedBy: CodingKeys.self)
// This attempt of decoding possible nodes doesn't work
if let trunkNode: TreePartNode<Trunk> = try container.decodeIfPresent( TreePartNode<Trunk>.self, forKey: .trunkNode ) {
self.init( trunkNode )
} else if let branchNode: TreePartNode<Branch> = try container
.decodeIfPresent( TreePartNode<Branch>.self, forKey: .branchNode ) {
self.init( branchNode )
} else if let appleNode: TreePartNode<Apple> = try container
.decodeIfPresent( TreePartNode<Apple>.self, forKey: .appleNode ) {
self.init( appleNode )
} else {
let context = DecodingError.Context( codingPath: [CodingKeys.trunkNode,
CodingKeys.branchNode,
CodingKeys.appleNode],
debugDescription: "Could not find the treePart node key" )
throw DecodingError.keyNotFound( CodingKeys.trunkNode, context )
}
// TODO recreating the connections between the nodes should happen after all objects are decoded and will be done based on the UUIDs
}
func encode( to encoder: Encoder ) throws {
var container = encoder.container( keyedBy: CodingKeys.self )
switch self.wrappedTreePartNode {
case let trunkNode as TreePartNode<Trunk>:
try container.encode( trunkNode, forKey: .trunkNode )
case let branchNode as TreePartNode<Branch>:
try container.encode( branchNode, forKey: .branchNode )
case let appleNode as TreePartNode<Apple>:
try container.encode( appleNode, forKey: .appleNode )
default:
fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePartNode ) )" )
}
}
}
extension AnyTreePartNode: Equatable {
static func ==( lhs: AnyTreePartNode, rhs: AnyTreePartNode ) -> Bool {
return lhs.wrappedTreePartNode.isEqualTo( rhs.wrappedTreePartNode )
}
}
// enables printing of the wrapped tree part and its child elements
extension AnyTreePartNode: CustomStringConvertible {
var description: String {
var text = "\( type( of: self.wrappedTreePartNode.treePart.wrappedTreePart ))"
if !self.children.isEmpty {
text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
}
return text
}
}
///////////// TreeParts (Trunk, Branch and Apple)
class Trunk: TreePart, Codable, Equatable {
var name: String
var color: String
init( name: String = "trunk",
color: String = "#CCC" ) {
self.name = name
self.color = color
}
static func ==(lhs: Trunk, rhs: Trunk) -> Bool {
return lhs.name == rhs.name &&
lhs.color == rhs.color
}
}
class Branch: TreePart, Codable, Equatable {
var name: String
var length: Int
init( name: String = "branch",
length: Int = 4 ) {
self.name = name
self.length = length
}
static func ==(lhs: Branch, rhs: Branch) -> Bool {
return lhs.name == rhs.name &&
lhs.length == rhs.length
}
}
class Apple: TreePart, Codable, Equatable {
var name: String
var size: Int
init( name: String = "apple",
size: Int = 2 ) {
self.name = name
self.size = size
}
static func ==(lhs: Apple, rhs: Apple) -> Bool {
return lhs.name == rhs.name &&
lhs.size == rhs.size
}
}
///////////// TreePartNode -> The node in the tree that contains the TreePart
class TreePartNode<T: TreePart>: TreePartNodeBase, Codable {
var equatableSelf: AnyTreePartNode!
var uuid: UUID
var treePart: AnyTreePart
var weakChildren = NSPointerArray.weakObjects()
private var parentUuid : UUID?
private var childrenUuids : [UUID]?
weak var parent: AnyTreePartNode? {
willSet {
if newValue == nil {
// unrelated code
// ... removes the references to this object in the parent node, if it exists
}
}
}
init( _ treePart: AnyTreePart,
uuid: UUID = UUID() ) {
self.treePart = treePart
self.uuid = uuid
self.equatableSelf = self.asEquatable()
}
convenience init( _ treePart: T,
uuid: UUID = UUID() ) {
self.init( treePart.asEquatable(),
uuid: uuid )
}
init( _ treePart: AnyTreePart,
uuid: UUID,
parentUuid: UUID?,
childrenUuids: [UUID]?) {
self.treePart = treePart
self.uuid = uuid
self.parentUuid = parentUuid
self.childrenUuids = childrenUuids
self.equatableSelf = self.asEquatable()
}
private func add( child: AnyTreePartNode ) {
child.parent = self.equatableSelf
self.weakChildren.addObject( child )
}
private func set( parent: AnyTreePartNode ) {
self.parent = parent
parent.weakChildren.addObject( self.equatableSelf )
}
// MARK: Codable
enum CodingKeys: String, CodingKey {
case treePart,
uuid,
parent,
children,
parentPort
}
required convenience init( from decoder: Decoder ) throws {
let container = try decoder.container( keyedBy: CodingKeys.self )
// non-optional values
let uuid: UUID = try container.decode( UUID.self, forKey: .uuid )
let treePart: AnyTreePart = try container.decode( AnyTreePart.self, forKey: .treePart )
// optional values
let childrenUuids: [UUID]? = try container.decodeIfPresent( [UUID].self, forKey: .children )
let parentUuid: UUID? = try container.decodeIfPresent( UUID.self, forKey: .parent )
self.init( treePart,
uuid: uuid,
parentUuid: parentUuid,
childrenUuids: childrenUuids)
}
func encode( to encoder: Encoder ) throws {
var container = encoder.container( keyedBy: CodingKeys.self )
// non-optional values
try container.encode( self.treePart, forKey: .treePart )
try container.encode( self.uuid, forKey: .uuid )
// optional values
if !self.children.isEmpty {
try container.encode( self.children.map { $0.uuid }, forKey: .children )
}
try container.encodeIfPresent( self.parent?.uuid, forKey: .parent )
}
}
extension TreePartNode: Equatable {
static func ==( lhs: TreePartNode, rhs: TreePartNode ) -> Bool {
return lhs.treePart == rhs.treePart &&
lhs.parent == rhs.parent &&
lhs.children == rhs.children
}
}
// enables printing of the wrapped tree part and its child elements
extension TreePartNode: CustomStringConvertible {
var description: String {
var text = "\( type( of: self.treePart.wrappedTreePart ))"
if !self.children.isEmpty {
text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
}
return text
}
}
// MARK: functions for adding connections to other TreeParts for each specific TreePart type
extension TreePartNode where T: Trunk {
func add( child branch: TreePartNode<Branch> ) {
self.add( child: branch.equatableSelf )
}
}
extension TreePartNode where T: Branch {
func add( child apple: TreePartNode<Apple> ) {
self.add( child: apple.equatableSelf )
}
func add( child branch: TreePartNode<Branch> ) {
self.add( child: branch.equatableSelf )
}
func set( parent branch: TreePartNode<Branch> ) {
self.set( parent: branch.equatableSelf )
}
func set( parent trunk: TreePartNode<Trunk> ) {
self.set( parent: trunk.equatableSelf )
}
}
extension TreePartNode where T: Apple {
func set( parent branch: TreePartNode<Branch> ) {
self.set( parent: branch.equatableSelf )
}
}
////////////// Helper
extension NSPointerArray {
func addObject( _ object: AnyObject? ) {
guard let strongObject = object else { return }
let pointer = Unmanaged.passUnretained( strongObject ).toOpaque()
self.addPointer( pointer )
}
}
关于ios - 在 Swift 4 中解码泛型类的可编码树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50011841/
这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下
我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上
当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#
当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab
我需要将目录中的一堆文件上传到S3。由于上传所需的90%以上的时间都花在了等待http请求完成上,所以我想以某种方式同时执行其中的几个。Fibers能帮我解决这个问题吗?它们被描述为解决此类问题的一种方法,但我想不出在http调用阻塞时我可以做任何工作的任何方法。有什么方法可以在没有线程的情况下解决这个问题? 最佳答案 我没有使用1.9中的纤程,但是1.8.6中的常规线程可以解决这个问题。尝试使用队列http://ruby-doc.org/stdlib/libdoc/thread/rdoc/classes/Queue.html查看文
在ruby中...我有一个由外部进程创建的IO对象,我需要从中获取文件名。然而我似乎只能得到文件描述符(3),这对我来说不是很有用。有没有办法从此对象获取文件名甚至获取文件对象?我正在从通知程序中获取IO对象。所以这也可能是获取文件路径的一种方式? 最佳答案 关于howtogetathefilenameinC也有类似的问题,我将在这里以ruby的方式给出这个问题的答案。在Linux中获取文件名假设io是您的IO对象。以下代码为您提供了文件名。File.readlink("/proc/self/fd/#{io.fileno}")例
文章目录前言核心逻辑配置iSH安装Python创建Python脚本配置启动文件测试效果快捷指令前言iOS快捷指令所能做的操作极为有限。假如快捷指令能运行Python程序,那么可操作空间就瞬间变大了。iSH是一款免费的iOS软件,它模拟了一个类似Linux的命令行解释器。我们将在iSH中运行Python程序,然后在快捷指令中获取Python程序的输出。核心逻辑我们用一个“获取当前日期”的Python程序作为演示(其实快捷指令中本身存在“获取当前日期”的操作,因而此需求可以不用Python,这里仅仅为了演示方便),核心代码如下。>>>importtime>>>time.strftime('%Y-%
我有一个使用postgresql的Rails4应用程序。我还有一个backbone.js应用程序,可将JSON推送到Rails4应用程序。这是我的Controller:defcreate@product=Product.new(ActiveSupport::JSON.decodeproduct_params)respond_todo|format|if@product.saveformat.json{renderaction:'show',status::created,location:@product}elseformat.json{renderjson:@product.erro