在 Swift 中将字符串拆分为数组? [英] Split a String into an array in Swift?

查看:38
本文介绍了在 Swift 中将字符串拆分为数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在这里有一个字符串:

Say I have a string here:

var fullName: String = "First Last"

我想根据空格分割字符串并将值分配给它们各自的变量

I want to split the string base on white space and assign the values to their respective variables

var fullNameArr = // something like: fullName.explode(" ") 

var firstName: String = fullNameArr[0]
var lastName: String? = fullnameArr[1]

此外,有时用户可能没有姓氏.

Also, sometimes users might not have a last name.

推荐答案

Swift 的方式是使用全局的 split 函数,像这样:

The Swift way is to use the global split function, like so:

var fullName = "First Last"
var fullNameArr = split(fullName) {$0 == " "}
var firstName: String = fullNameArr[0]
var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil

使用 Swift 2

在 Swift 2 中,由于引入了内部 CharacterView 类型,split 的使用变得有点复杂.这意味着 String 不再采用 SequenceType 或 CollectionType 协议,您必须改为使用 .characters 属性来访问 String 实例的 CharacterView 类型表示.(注意:CharacterView 确实采用了 SequenceType 和 CollectionType 协议).

In Swift 2 the use of split becomes a bit more complicated due to the introduction of the internal CharacterView type. This means that String no longer adopts the SequenceType or CollectionType protocols and you must instead use the .characters property to access a CharacterView type representation of a String instance. (Note: CharacterView does adopt SequenceType and CollectionType protocols).

let fullName = "First Last"
let fullNameArr = fullName.characters.split{$0 == " "}.map(String.init)
// or simply:
// let fullNameArr = fullName.characters.split{" "}.map(String.init)

fullNameArr[0] // First
fullNameArr[1] // Last 

这篇关于在 Swift 中将字符串拆分为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆