简体   繁体   English

如何在 Swift 中使用相同的变量名,但使用不同的数据类型

[英]how can I do to use same variable name, but different data type in Swift

I get error when I was assigned the different value in same variable name.当我在相同的变量名中分配不同的值时出现错误。

This is the error: cannot assign value of type '[String]' to type 'String' and this is the code:这是错误:无法将“[String]”类型的值分配给“String”类型,这是代码:

var data: String

data = "datas|datas"
data = data.components(separatedBy: "|") as! [String]
debugPrint(data.first!)

or, this is for image in code type:或者,这是针对代码类型的图像:

图像代码

I think, in PHP language, is more easier than Swift language.我认为,在 PHP 语言中,比 Swift 语言更容易。 Because, in PHP language, this code is run as it should.因为,在 PHP 语言中,此代码按其应有的方式运行。

hope somebody help me out希望有人帮助我

No you can't不,你不能

let other = data.components(separatedBy: "|") as! [String]

you have to set a variable to only 1 type at a time , makeing data of type any will do the job but you have to cast您必须一次将变量设置为一种类型,使any类型的data any可以完成这项工作,但您必须进行强制转换

I would suggest just use array of strings always:我建议始终使用字符串数组:

var data: [String]

data = ["datas|datas"]
data = data.flatMap { $0.components(separatedBy: "|") }
debugPrint(data.first!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用与String Swift同名的变量 - How to use variable with the same name as String Swift Swift:如何使用“ AnyClass”变量定义数组内部的类型? - Swift: how can I use an 'AnyClass' variable to define what type is inside an array? 如何同时使用swift 2和swift 3? - How can I use swift 2 and swift 3 at the same time? 如何使用 Swift 在 Firebase 中存储具有相同关键字的不同数据的多个实例? - How can I store multiple instances of different data with the same keyword in Firebase using Swift? 如何在Swift中将类名指定为变量? - How do I specify class name as variable in Swift? 如何将 Firestore 数据存储在可以在 Swift/Xcode 中操作的变量中? - How do I store Firestore data in a variable that I can manipulate in Swift/Xcode? 如何在Swift扩展中声明NSLayoutConstraint类型的变量 - How do i declare a variable of type NSLayoutConstraint in an extension in swift 如何使用Swift对数组数组进行排序(按变量名)? - How can I sort an array of arrays (by variable name) using Swift? 如何在Swift中的同一UILabel上淡入和淡出不同文本? - how can I fade in and out different texts on the same UILabel in Swift? 如何使用快速字符串的值作为要编辑的UIObject的名称? - How can I use the value of a swift string as the name of an UIObject to edit?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM