Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift:创建NSXMLNode_Xml_Swift_Nsxmlnode - Fatal编程技术网

Swift:创建NSXMLNode

Swift:创建NSXMLNode,xml,swift,nsxmlnode,Xml,Swift,Nsxmlnode,我正在尝试使用Swift创建一个NSXMLNode。基于(以及Xcode的自动完成),这看起来应该非常简单: 但我得到一个错误:“调用中缺少参数‘URI’的参数。” 然后我尝试: var anAttribute: NSXMLNode = NSXMLNode.attributeWithName("name", URI: "uri", stringValue: "string") 这会产生同样令人迷惑的错误:“调用中的额外参数‘URI’。” 有人能告诉我这里发生了什么吗?attributeWith

我正在尝试使用Swift创建一个NSXMLNode。基于(以及Xcode的自动完成),这看起来应该非常简单:

但我得到一个错误:“调用中缺少参数‘URI’的参数。”

然后我尝试:

var anAttribute: NSXMLNode = NSXMLNode.attributeWithName("name", URI: "uri", stringValue: "string")
这会产生同样令人迷惑的错误:“调用中的额外参数‘URI’。”

有人能告诉我这里发生了什么吗?

attributeWithName()
返回
任何对象?
,即
id
的快速映射。所以你 必须将返回值强制转换为预期类型:

let anAttribute = NSXMLNode.attributeWithName("name", stringValue: "string") as NSXMLNode
或者,如果要检查可能的故障:

if let anAttribute = NSXMLNode.attributeWithName("name", stringValue: "string") as? NSXMLNode {
    // success
} else {
    // failed
}

根本原因是Objective-C函数

+ (id)attributeWithName:(NSString *)name stringValue:(NSString *)value
返回
id
。如果它被宣布为

+ (instancetype)attributeWithName:(NSString *)name stringValue:(NSString *)value
(这是声明类/工厂方法的“现代”方式)那么 映射到Swift as

 class func attributeWithName(_ name: String!,
             stringValue value: String!) -> NSXMLNode!
使显式强制转换变得不必要。 你可以就此向苹果公司提交一份缺陷报告

 class func attributeWithName(_ name: String!,
             stringValue value: String!) -> NSXMLNode!