how can i change randomly the character orders in a string?
example, Input: hello - Output: elolh
You can use List.shuffle :
var text = 'HELLO';
// First turn you text into a List :
List list = text.split('');
// Shuffle the list :
list.shuffle();
// Then turn back the list into a String
String shuffled = list.join();
print(shuffled); // LLHOE
One-liner :
String shuffled = ('HELLO'.split('')..shuffle()).join();
Extension method :
void main() {
var text = 'HELLO';
var shuffled = text.shuffled();
print(shuffled); // OLEHL
}
extension on String {
String shuffled() =>
(this.split('')..shuffle()).join();
}
Related
I have two Array with different Data Types
Assume Array1 is an [String] array of String
Assume Array 2 is an [Custom Objects] array of Struct
Pls find a code
struct ScanData{
var serialNo : String!
var intNo : String!
init(serialNo : String, intNo : String) {
self.serialNo = serialNo
self.intNo = intNo
}
}
var validScannedData : [String] = []
var inValidScannedData : [String] = []
var arrayObj = [ScanData(serialNo: "12220116033", intNo: "SN6AT4.270"),ScanData(serialNo: "12198144025", intNo: "SN6AT4.280"),ScanData(serialNo: "12222383027", intNo: "SN6AT4.130"),ScanData(serialNo: "12198213032", intNo: "SN6AT5.260"),ScanData(serialNo: "", intNo: "")]
//print(arrayObj)
//ScanData(serialNo: "12199690049", intNo: "SN6AT6U100")
var localArray = ["12220116033","12198144025","12222383027","12198213032","12199690049"]
let tempArray = arrayObj.filter { data in
return data.serialNo != "" || data.intNo != ""
}
print(tempArray.count)
Now we want to get common values from localArray and tempArray by matching serialNo key
Finally i want to have Array of String Format in validScannedData object
Expected Output :
Valid data : ["12220116033","12198144025","12222383027","12198213032"]
Invalid data : ["12199690049"]
I tried this but its prints custom object array
let a = tempArray.filter () { localArray.contains($0.serialNo) }
print(a)
Thanks in advance
Use forEach to iterate your element and then check and append to the according to array.
localArray.forEach { number in
arrayObj.contains(where: {$0.serialNo == number}) ? validScannedData.append(number) : inValidScannedData.append(number)
}
print(validScannedData)
print(inValidScannedData)
I have an array like:-
var arrayData : Array<Dictionary<String, [BottleModel]>> = []
Bottle model :-
class BottleModel: NSObject {
var name : String
var price : Int
var reviews : Int
var category : String
var quantity : String
var id : String
var shopData : ShopModel
}
I want filtered array where price is > 2000
I tried let searchByInts = arrayData.filter({m in m.price < 200})
but getting below error:
Contextual closure
type '(Dictionary) -> Bool' expects 1 argument,
but 0 were used in closure body
How to filter such kind of array based on price
Working code:
let searchByInts = arrayData.filter { $0.values.contains { $0.contains { $0.price > 2000 } } }
By the way please write the following using literals:
var arrayData : [[String : [BottleModel]]] = []
Still no idea if that is what you actually want because your goal is very unclear. You have an array of dictionaries of arrays which actually contain the values you want to filter out. If a BottleModel costs more than 2000 do you want to keep the entire array it is contained in and the dictionary that array is in? You might want to map the entire data into one flat array before or after filtering.
Alternative using flatMap:
let flat = arrayData.flatMap { $0.values.flatMap { $0 } }
let searchByInts2 = flat.filter { $0.price < 200 } // or some other criteria
I have successfully mapped a Single key to single value like this:
class DefaultDoubleModel :BaseObject
{
var key : String = ""
var value : String = ""
}
var toolChart :[DefaultDoubleModel]!
self.BubbleChartXaxislabel = Array(GraphDataModel.toolChart.map({ (item) -> String in
item.key
}))
self.BubbleChartValuesGraph = Array(GraphDataModel.toolChart.map({ (item) -> String in
item.value
}))
This is true for single key and single value. But i have two values in a single key. How can i collect those values in array.
For example i have like this..
{"value2":"80","value1":"120","key":"4"}
A Dictionary with tuples of strings would look like this:
var data: [String: (String, String)]()
data["4"] = ("80", "120")
print(data["4"]!.0)
You access the elements as .0 and .1.
If you want exactly two values, then you can make your DefaultDoubleModel look like this
class DefaultDoubleModel :BaseObject {
var key : String = ""
var value1 : String = ""
var value2 : String = ""
}
I think its more future proof to make it an array of Strings, like this:
class DefaultDoubleModel :BaseObject {
var key : String = ""
var values = [String]()
}
If you go with the second option, then you would map like this:
self.BubbleChartValuesGraph = GraphDataModel.toolChart.flatMap{ $0.values }
I have a Profile Data singleton class as follows.
I am trying to store data into an empty array in a dictionary .
After appending data to the array also the count of the array is 0.
class ProfileData{
static let sharedInstance = ProfileData()
var artistProfileDict = [String : Profile]()
var loggedInUserProfile = Profile(artistName: "John Smith", artistDescription: "Admiral of New England, English soldier, explorer, and author.", totalLikes: "174", totalViews: "200", totalFollowing: "100",totalFollowers:"50",imageUrl:"image_singer", feeds:[] )
private init() {
getProfilesDictionary()
}
func getProfilesDictionary()->[String: Profile]{
artistProfileDict["John Smith"] = loggedInUserProfile
return artistProfileDict
}
func add(array: Feed, artistName: String) {
artistProfileDict[artistName]!.feeds.append(array)
}
}
In another view Controller I am trying to add an array to the empty array in the dictionary as follows
let newFeed = Feed(profilePicture: "image",artistName: "New",
videoUrl: "url",videoTitle:"New", videoViews: "160",likes:
"200",shoutouts: "200",comments: [],votes: "50", dateCreated: Date(),
userActivity :"This user liked your video")
ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")
After appending the array to the empty array in the dictionary I still get the count of the array as 0.
I am not able to figure out the problem here. Any help will appreciated . Thank you.
Profile class
struct Profile {
var artistName: String
var artistDescription: String
var totalLikes: String
var totalViews: String
var totalFollowing: String
var totalFollowers: String
var imageUrl: String
var feeds : [Feed]
init(artistName: String,artistDescription:String,totalLikes:String,totalViews:String,totalFollowing:String,totalFollowers:String,imageUrl:String, feeds:[Feed]) {
self.artistName = artistName
self.artistDescription = artistDescription
self.totalLikes = totalLikes
self.totalViews = totalViews
self.totalFollowing = totalFollowing
self.totalFollowers = totalFollowers
self.imageUrl = imageUrl
self.feeds = feeds
}
}
It's working fine
ProfileData.sharedInstance.add(array: newFeed,artistName:"John Smith")
ProfileData.sharedInstance.artistProfileDict["John Smith"]?.feeds.count // 1
Probably you are using wrong class ArtistProfileData instead of ProfileData.
I have an array with student objects and another array with goodStrudentId. I need to fetch all the student objects from students array following sequence of goodStrudentId.
Using multiple forloop i can able to solve this, but i want to learn the best way to solve this issue. My only problem is following sequence of goodStrudentId.
Here is a sample code to understand my problem -
class Student {
var s_id : String
var s_name : String
init(i: String, n: String) {
self.s_id = i;
self.s_name = n;
}
}
var students = [Student(i: "1",n: "a"),
Student(i: "2",n: "b"),
Student(i: "3",n: "c"),
Student(i: "4",n: "d"),
Student(i: "5",n: "e")]
var goodStudentsId = ["5","2"]
var goodStudentObject = getGoodStudentObjectUsingId(students:students, gdStudentsId:goodStudentsId)
/*
Expected answer:
var goodStudentObject = [Student(i: "5",n: "e"), Student(i: "2",n: "b")]
*/
func getGoodStudentObjectUsingId(students:Array<Student>, gdStudentsId:Array<String>) -> Array<Student>! {
/*?????? please complete this func*/
return [];
}
func getGoodStudentObjectUsingId(students:[Student], gdStudentsId:[String]) -> [Student] {
return students.filter {
gdStudentsId.contains($0.s_id)
}
}