সুইফট 3-এর জন্য আপডেট করা হয়েছে
নীচের উত্তরটি উপলব্ধ বিকল্পগুলির সংক্ষিপ্তসার। আপনার প্রয়োজন অনুসারে সবচেয়ে উপযুক্ত একটি নির্বাচন করুন।
reversed: একটি পরিসরে সংখ্যা
অগ্রবর্তী
for index in 0..<5 {
print(index)
}
// 0
// 1
// 2
// 3
// 4
অনগ্রসর
for index in (0..<5).reversed() {
print(index)
}
// 4
// 3
// 2
// 1
// 0
reversed: মধ্যে উপাদান SequenceType
let animals = ["horse", "cow", "camel", "sheep", "goat"]
অগ্রবর্তী
for animal in animals {
print(animal)
}
// horse
// cow
// camel
// sheep
// goat
অনগ্রসর
for animal in animals.reversed() {
print(animal)
}
// goat
// sheep
// camel
// cow
// horse
reversed: সূচকযুক্ত উপাদান
কখনও কখনও সংগ্রহের মাধ্যমে পুনরাবৃত্তি করার সময় একটি সূচক প্রয়োজন হয়। তার জন্য আপনি ব্যবহার করতে পারেন enumerate(), যা একটি টুপল ফেরত দেয়। টিপলের প্রথম উপাদানটি সূচক এবং দ্বিতীয় উপাদানটি হ'ল অবজেক্ট।
let animals = ["horse", "cow", "camel", "sheep", "goat"]
অগ্রবর্তী
for (index, animal) in animals.enumerated() {
print("\(index), \(animal)")
}
// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat
অনগ্রসর
for (index, animal) in animals.enumerated().reversed() {
print("\(index), \(animal)")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
নোট করুন যে বেন লাচম্যান তার উত্তরে উল্লেখ করেছেন , আপনি সম্ভবত এর .enumerated().reversed()চেয়ে বেশি করতে চান .reversed().enumerated()(যা সূচকের সংখ্যা বাড়িয়ে তুলবে)।
পদক্ষেপ: সংখ্যা
স্ট্রাইড একটি ব্যাপ্তি ব্যবহার না করে পুনরাবৃত্তি করার উপায়। দুটি রূপ আছে। কোডের শেষে দেওয়া মন্তব্যগুলি পরিসীমা সংস্করণটি কী হবে তা দেখায় (বর্ধিত আকার 1 বলে ধরে নেওয়া)।
startIndex.stride(to: endIndex, by: incrementSize) // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex
অগ্রবর্তী
for index in stride(from: 0, to: 5, by: 1) {
print(index)
}
// 0
// 1
// 2
// 3
// 4
অনগ্রসর
বর্ধিত আকার পরিবর্তন করা -1আপনাকে পিছনে যেতে দেয়।
for index in stride(from: 4, through: 0, by: -1) {
print(index)
}
// 4
// 3
// 2
// 1
// 0
toএবং throughপার্থক্য নোট করুন ।
স্ট্রাইড: সিকোয়েন্সটাইপের উপাদান
2 এর ইনক্রিমেন্ট দ্বারা ফরওয়ার্ড করুন
let animals = ["horse", "cow", "camel", "sheep", "goat"]
আমি 2এই উদাহরণটি ব্যবহার করছি অন্য একটি সম্ভাবনা দেখানোর জন্য।
for index in stride(from: 0, to: 5, by: 2) {
print("\(index), \(animals[index])")
}
// 0, horse
// 2, camel
// 4, goat
অনগ্রসর
for index in stride(from: 4, through: 0, by: -1) {
print("\(index), \(animals[index])")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
মন্তব্য