Skip to content

Commit

Permalink
Merge pull request #13 from Isvvc/chaining
Browse files Browse the repository at this point in the history
Chaining
  • Loading branch information
chenyunguiMilook authored Jul 18, 2020
2 parents e77c9bb + 94b7ce4 commit fa7a359
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
18 changes: 11 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,17 +172,21 @@ if let c: Color = xml.product.catalog_item.size.color_swatch.enum() {

```swift
let store = XML(name: "store")
store.addAttribute(name: "description", value: "Ball Store")

let product1 = XML(name: "product")
product1.addAttribute(name: "name", value: "football")
product1.addAttribute(name: "weight", value: 0.453)

.addAttribute(name: "description", value: "Ball Store")
.addChildren([
// attributes can be added in the initializer
XML(name: "product", attributes: [
"name": "football",
"weight": 0.453
])
])

// attributes can be added to an existing object
let product2 = XML(name: "product")
product2.addAttribute(name: "name", value: "basketball")
product2.addAttribute(name: "weight", value: 0.654)

store.addChild(product1)
// children can be added to an existing object
store.addChild(product2)

print(store.toXMLString())
Expand Down
16 changes: 12 additions & 4 deletions Sources/SwiftyXML/XML.swift
Original file line number Diff line number Diff line change
Expand Up @@ -279,26 +279,34 @@ open class XML {
}
}

public func addAttribute(name:String, value:Any) {
@discardableResult
public func addAttribute(name:String, value:Any) -> XML {
self.attributes[name] = String(describing: value)
return self
}

public func addAttributes(_ attributes:[String : Any]) {
@discardableResult
public func addAttributes(_ attributes:[String : Any]) -> XML {
for (key, value) in attributes {
self.addAttribute(name: key, value: value)
}
return self
}

public func addChild(_ xml:XML) {
@discardableResult
public func addChild(_ xml:XML) -> XML {
guard xml !== self else {
fatalError("can not add self to xml children list!")
}
children.append(xml)
xml.parent = self
return self
}

public func addChildren(_ xmls: [XML]) {
@discardableResult
public func addChildren(_ xmls: [XML]) -> XML {
xmls.forEach{ self.addChild($0) }
return self
}
}

Expand Down

0 comments on commit fa7a359

Please sign in to comment.