所以我有全名文本字段,我通过按空格分割完整名称来创建nameComponents
数组。现在我想将0索引元素作为名字,其余组件作为姓氏。我喜欢this在Swift中加入字符串数组的方法。有没有办法从特定索引(在我的情况下索引1)开始加入数组。我不想使用循环。
答案 0 :(得分:2)
您可以使用Mockito mock of SecurityManager throwing an exception或dropFirst()
<强> dropFirst()强>
let names = "It is a long name".components(separatedBy: " ")
let lastName = names.dropFirst(2).joined(separator: " ")
print(lastName)//a long name
<强> dropFirst(_:)强>
axios.get('../assets/json/ar/myfile.json')
.then(response => {
// JSON responses are automatically parsed.
console.log(response)
})
.catch(e => {
this.errors.push(e)
})
答案 1 :(得分:1)
如果您只想在第一个空格中分隔字符串,则无需将字符串完全拆分为数组。 您可以找到第一个空格并直接确定其前后的部分。 示例(Swift 3):
let string = "foo bar baz"
if let range = string.range(of: " ") {
let firstPart = string.substring(to: range.lowerBound)
let remainingPart = string.substring(from: range.upperBound)
print(firstPart) // foo
print(remainingPart) // bar baz
}
在Swift 4中,您将使用
提取部件 let firstPart = String(string[..<range.lowerBound])
let remainingPart = String(string[range.upperBound...])
答案 2 :(得分:0)
尝试使用Swift3:
let array = ["zero", "one", "two", "three"]
let str = array[1..<array.count].joined(separator: "-")
// po str
// "one-two-three"
答案 3 :(得分:0)
对于这个问题,您可以这样做:
示例:
var nameComponents = ["My", "name", "is"]
let firstName = nameComponents.remove(at: 0) // "My"
let lastName = nameComponents.joined(separator: " ") // "name is"
但更实际的方法是使用array subscript by passing Range
。
let firstName = nameComponents.first!
// Swift 3
let lastName = nameComponents[1..<nameComponents.count].joined(separator: " ")
// Swift 4
let lastName = nameComponents[1...].joined(separator: " ")