博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
如何将Swift数组转换为字符串?
阅读量:2291 次
发布时间:2019-05-09

本文共 4898 字,大约阅读时间需要 16 分钟。

本文翻译自:

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楼

参考:


#2楼

If the array contains strings, you can use the String 's join method: 如果数组包含字符串,则可以使用Stringjoin方法:

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 becomes joined , example [nil, "1", "2"].flatMap({$0}).joined() join变得joined ,例如[nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(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_result    public 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"

转载地址:http://xzjnb.baihongyu.com/

你可能感兴趣的文章
Robots Meta Tag的使用
查看>>
Robots.txt指南
查看>>
搜索引擎和网站的目录结构
查看>>
实战中文搜索引擎推广
查看>>
搜索引擎与spam
查看>>
简谈搜索引擎工作流程
查看>>
索引擎控制关系
查看>>
学习搜索的网站
查看>>
网络搜索引擎与智能代理技术
查看>>
Perl DBI连接MySQL数据库
查看>>
Perl DBI 入门
查看>>
debian 下 perldoc 安装
查看>>
perl CPAN模块安装的配置文件
查看>>
常用vi指命
查看>>
php5 面向对像学习手扎
查看>>
IE 下的打印
查看>>
一个Mysql自动备份脚本
查看>>
常用Linux软件列表
查看>>
vi的使用
查看>>
Red Hat下WEB服务器的配置
查看>>