

["さとう","あおき"、"おおの"]というように名前の文字列が入っている配列を、  
「"あおき"、"おおの"、"さとう"」というように五十音順に並び変えるにはどのような方法が  
ありますか？

[code]

    class person :NSObject{
    
        var name : NSString?
    
        init(nam:NSString) {
    
        name = nam
        }
    
    }
    
    
    var person1 = person(nam: "おおの")
    var person2 = person(nam: "さとう")
    var person3 = person(nam: "あおき")
    
    println(person1.name)
    println(person2.name)
    println(person3.name)
    
[/code]

このようなインスタンスが入った配列の場合も同様に可能でしょうか？


CC BY-SA 3.0
2015-06-29T06:14:53.050
11843
2015-06-29T08:32:37.380
2015-06-29T07:12:47.413
8060
8060
question
swift
Swiftの配列の要素を五十音順に並べたい。


このように出来ます。

[code]

    var strings = ["さとう", "あおき", "おおの", "かみきど", "すずき"]
    sort(strings) { str1, str2 in str1 > str2 }
    
    strings.sort { (lhs, rhs) in return lhs < rhs }
    
[/code]

<http://qiita.com/mst/items/b18e9531ac0cbdf2f3c3>

編集

[code]

    class person {
    
        var name : NSString
    
        init(nam:NSString) {
    
            name = nam
        }
    
    }
    
    
    var person1 = person(nam: "おおの")
    var person2 = person(nam: "さとう")
    var person3 = person(nam: "あおき")
    
    var people: Array<person> = []
    
    
    people += [person1]
    people += [person2]
    people += [person3]
    
    var sortedPeople = people.sorted({ ($0.name as? String) < ($1.name as? String)  })
    
    
    println(person1.name)
    println(person2.name)
    println(person3.name)
    
    println(sortedPeople[0].name)
    println(sortedPeople[1].name)
    println(sortedPeople[2].name)
    
[/code]

もし片仮名対応も出来たいのなら、こんなふうに出来ます。

[code]

    extension String {
        func hiragana() -> String {
            var str = ""
            for c in unicodeScalars {
                if c.value >= 0x30A1 && c.value <= 0x30F6 {
                    str.append(UnicodeScalar(c.value-96))
                } else {
                    str.append(c)
                }
            }
            return str
        }
    }
    class person {
    
        var name : NSString
    
        init(nam:NSString) {
    
            name = nam
        }
    
    }
    
    
    var person1 = person(nam: "おおの")
    var person2 = person(nam: "さとう")
    var person3 = person(nam: "あおき")
    var person4 = person(nam: "カミキド")
    
    var people: Array<person> = []
    
    
    people += [person1]
    people += [person2]
    people += [person3]
    people += [person4]
    
    var sortedPeople = people.sorted({ ($0.name as String).hiragana() < ($1.name as String).hiragana()  })
    
    
    println(person1.name)  //おおの
    println(person2.name)  //さとう
    println(person3.name)  //あおき
    println(person4.name)　//カミキド
    
    println(sortedPeople[0].name)  //あおき
    println(sortedPeople[1].name)  //おおの
    println(sortedPeople[2].name)  //カミキド
    println(sortedPeople[3].name)　//さとう
    
[/code]


CC BY-SA 3.0
2015-06-29T06:30:04.120
11844
2015-06-29T08:32:37.380
2015-06-29T08:32:37.380
4336
4336
11843
answer