How to get first letter of all strings in an array in iOS Swift?

我的未来我决定 提交于 2019-12-09 15:57:20

问题


I have a group of strings stored in an array.

stringArray = [Aruna, Bala, Chitra, Divya, Fatima]

I want to get the first letters of all the strings and store it in an array. Like: letterArray = [A, B, C, D, F]

Note: They are not within quotes "--"


回答1:


Not sure what you mean by 'they are not within quotes', but if they are actually Strings then something like this:

var letterArray = [Character]()
for string in stringArray {
    letterArray.append(string.characters.first!)
}

EDIT

To have it as String instead as you wish:

var letterArray = [String]()
for string in stringArray {
    letterArray.append(String(string.characters.first!))
}

EDIT 2

As Leo Dabus suggests, if you pass an empty string the above will fail. If you know there will never be an empty string this doesn't apply, but I've updated the above to handle this case:

var letterArray = [String]()
for string in stringArray {
    if let letter = string.characters.first {
        letterArray.append(String(letter))
    }
}

UPDATE: SWIFT 4

From Swift 4 characters has been deprecated. Instead of using string.characters.first you should now operate on the String directly using just string.first. For example:

var letterArray = [String]()
for string in stringArray {
    if let letter = string.first {
        letterArray.append(String(letter))
    }
}



回答2:


Xcode 9 • Swift 4

extension Collection where Element: StringProtocol {
    var initials: [Element.SubSequence] {
        return map { $0.prefix(1) }
    }
}

Xcode 8 • Swift 3

extension Collection where Iterator.Element == String {
    var initials: [String] {
        return map{String($0.characters.prefix(1))}
    }
}

Xcode 7.3.1 • Swift 2.2.1

extension CollectionType where Generator.Element == String {
    var initials: [String] {
        return map{ String($0.characters.prefix(1)) }
    }
}


let stringArray = ["Aruna", "Bala", "Chitra", "Divya", "Fatima"]

let initials = stringArray.initials  // ["A", "B", "C", "D", "F"]


来源:https://stackoverflow.com/questions/33792991/how-to-get-first-letter-of-all-strings-in-an-array-in-ios-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!