如何将Swift数组转换为字符串?
本文翻译自:How do I convert a Swift Array to a String?
I know how to programmatically do it, but I'm sure there's a built-in way... 我知道如何以编程方式进行操作,但是我敢肯定有一种内置方法...
Every language I've used has some sort of default textual representation for a collection of objects that it will spit out when you try to concatenate the Array with a string, or pass it to a print() function, etc. Does Apple's Swift language have a built-in way of easily turning an Array into a String, or do we always have to be explicit when stringifying an array? 我使用的每种语言都有一组对象的默认文本表示形式,当您尝试将Array与字符串连接起来或将其传递给print()函数时,它将吐出。Apple的Swift语言是否可以有一种轻松地将数组转换为字符串的内置方法,还是在对数组进行字符串化时始终必须明确?
#1楼
参考:https://stackoom.com/question/1kMn3/如何将Swift数组转换为字符串
#2楼
If the array contains strings, you can use the String
's join
method: 如果数组包含字符串,则可以使用String
的join
方法:
var array = ["1", "2", "3"]let stringRepresentation = "-".join(array) // "1-2-3"
In Swift 2 : 在Swift 2中 :
var array = ["1", "2", "3"]let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
This can be useful if you want to use a specific separator (hypen, blank, comma, etc). 如果要使用特定的分隔符(连字符,空格,逗号等),这可能很有用。
Otherwise you can simply use the description
property, which returns a string representation of the array: 否则,您可以简单地使用description
属性,该属性返回数组的字符串表示形式:
let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"
Hint: any object implementing the Printable
protocol has a description
property. 提示:任何实现Printable
协议的对象都具有description
属性。 If you adopt that protocol in your own classes/structs, you make them print friendly as well 如果您在自己的类/结构中采用该协议,则也使它们易于打印
In Swift 3 在Swift 3中
join
becomesjoined
, example[nil, "1", "2"].flatMap({$0}).joined()
join
变得joined
,例如[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomesjoined(separator:)
(only available to Array of Strings)joinWithSeparator
变为joinWithSeparator
joined(separator:)
(仅适用于字符串数组)
In Swift 4 在Swift 4中
var array = ["1", "2", "3"]
array.joined(separator:"-")
#3楼
The Swift equivalent to what you're describing is string interpolation. 与您描述的Swift等效的是字符串插值。 If you're thinking about things like JavaScript doing "x" + array
, the equivalent in Swift is "x\\(array)"
. 如果您考虑使用JavaScript做"x" + array
类的事情,那么Swift中的等效项就是"x\\(array)"
。
As a general note, there is an important difference between string interpolation vs the Printable
protocol. 作为一般说明,字符串插值与Printable
协议之间存在重要区别。 Only certain classes conform to Printable
. 仅某些类符合Printable
。 Every class can be string interpolated somehow. 每个类都可以以某种方式插入字符串。 That's helpful when writing generic functions. 这在编写泛型函数时很有用。 You don't have to limit yourself to Printable
classes. 您不必仅限于Printable
类。
#4楼
Swift 2.0 Xcode 7.0 beta 6 onwards uses joinWithSeparator()
instead of join()
: Swift 2.0 Xcode 7.0 beta 6及更高版本使用joinWithSeparator()
而不是join()
:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
joinWithSeparator
is defined as an extension on SequenceType
joinWithSeparator
被定义为SequenceType
的扩展
extension SequenceType where Generator.Element == String {/// Interpose the `separator` between elements of `self`, then concatenate/// the result. For example:////// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"@warn_unused_resultpublic func joinWithSeparator(separator: String) -> String
}
#5楼
Mine works on NSMutableArray with componentsJoinedByString 我的工作与组件JoinedByString NSMutableArray
var array = ["1", "2", "3"]
let stringRepresentation = array.componentsJoinedByString("-") // "1-2-3"
#6楼
With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem. 使用Swift 5,您可以根据需要选择以下Playground示例代码之一来解决您的问题。
Turning an array of Character
s into a String
with no separator: 将Character
数组转换为不带分隔符的String
:
let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)print(string)
// prints "John"
Turning an array of String
s into a String
with no separator: 将String
数组转换为不带分隔符的String
:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")print(string) // prints: "BobDanBryan"
Turning an array of String
s into a String
with a separator between words: 将String
数组转换为单词之间带有分隔符的String
:
let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")print(string) // prints: "Bob Dan Bryan"
Turning an array of String
s into a String
with a separator between characters: 将String
数组转换为在字符之间使用分隔符的String
:
let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { $0 }
let stringArray2 = characterArray.map { String($0) }
let string = stringArray2.joined(separator: ", ")print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"
Turning an array of Float
s into a String
with a separator between numbers: 将Float
数组转换为String
,并在数字之间使用分隔符:
let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String($0) }
let string = stringArray.joined(separator: "-")print(string)
// prints "12.0-14.6-35.0"
如何将Swift数组转换为字符串?相关推荐
- 如何将零终止的字节数组转换为字符串?
本文翻译自:How to convert a zero-terminated byte array to string? I need to read [100]byte to transfer a ...
- flash与字符串:数组转换为字符串
//将数组转换为字符串 function getArrayString(array:Array):String { var len:int=array.length; if(len==0) retur ...
- sql数组转换为字符串
将数组转换为字符串 利用 ARRAY_TO_STRING() 函数,您可以将 ARRAY 转换为单个 STRING 值,或者将 ARRAY 转换为单个 BYTES 值,其中,生成的值是有序连接的数组元 ...
- scala 字符串转换数组_如何在Scala中将字节数组转换为字符串?
scala 字符串转换数组 Byte Array in Scala is an array of elements of a byte type. String in Scala is a colle ...
- java中字节数组转换为字符串
1.字节数组转换为字符串 byte[] byBuffer = new byte[20]; ... ... String strRead = new String(byBuffer); strRead= ...
- html5将数组转换为字符串,js如何将数组元素转换为字符串
数组转换为字符串代码实例-51前端 window.οnlοad=function(){ var mian=document.getElementById("mian"); var ...
- JS学习26:数组对象 之 数组转换为字符串
数组中有把数组转化为字符串的方法,部分方法如下表 注意:join方法如果不传入参数,则按照 " , "拼接元素 // 数组转换为字符串 // 1. toString() 将我们的数 ...
- java 字符串数组 转字符串_Java 中将字符串数组转换为字符串
Java 中将字符串数组转换为字符串 import java.util.Arrays; import java.util.HashSet; import java.util.Set; public c ...
- html5将数组转换为字符串,JavaScript怎么将数组转字符串?
JavaScript 允许数组与字符串之间相互转换.其中 Array 方法对象定义了 3 个方法,可以把数组转换为字符串.数组方法说明 toString()将数组转换成一个字符串 toLocalStr ...
最新文章
- 阿里巴巴电商平台架构演变之路
- node11---相册
- AsyncSocket
- 一道考查request导致的安全性问题的ctf题
- 2017-2018-1 20179215 《从问题到程序》第三章
- EmEditor 常用功能
- 西南科技大学OJ题 约瑟夫问题的实现0956
- HNOI2004宠物收养所
- win10删除*某些设置由你的组织来管理
- Java项目:SSH高校科研管理系统平台
- VMware新建OracleLinux6.5虚拟机
- python dict排序_python 字典(dict)按键和值排序
- Fragment的懒加载与生命周期详解
- 自定义交叉熵损失函数的几个问题
- 极几何,本质矩阵,基础矩阵,单应矩阵,相机投影矩阵
- kali linux不用网卡驱动,Kali Linux ——在无网络情况下安装无线网卡驱动
- 有所为而读与无所为而读—读李敖读书
- 华擎、映泰主板的网络唤醒(WOL)实例
- 联通3gnet服务器不稳定,彻底和3G网络说拜拜 中国联通猛发力 调整频段全面淘汰3G...
- linux驱动管理程序,linux设备驱动程序之时钟管理(4)----原来是孩儿他爹娘
热门文章
- 通过ApplicationContextAware加载Spring上下文环境
- Android RecycleView ScrollBy不生效
- 现在无法停止通用卷设备_软化和柔顺有什么区别吗?头发粗硬适合拉直还是烫卷?...
- Android之EventBus框架源码解析上(单例模式)
- linux怎么查看mysql安装在哪里_Linux下查看MySQL的安装路径
- pycharm安装scrapy失败_运行Scrapy程序时出现No module named win32api问题的解决思路和方法...
- codeforces685B
- hive常见问题及解决方法
- mysql免安装教程
- 下载jdk文件后缀是.gz而不是.tar.gz怎么办