String data= '[1, 2, 3]';
i want to convert my string to List<int>
expectations: [1, 2, 3]
what i got using my code:
print(json.decode(data));
result: 1
dataType: int
You can do this,
import 'dart:convert';
var list = json.decode(data);
Related
Eg: - Array of integers - [3,3,6] to [[1,2,3],[1,2,3],[1,2,3,4,5,6]]
lazy var arrCount = 3
lazy var numberCount = [Int]()
lazy var someArr = [SomeArr]()
for i in 0 ..< self!. arrCount.count {
self?.numberCount.append(self!.arrCount[I].someArr!.count)
}
print(self?.numberCount.count) // now response based on above example prints [3,3,6]
Response [3,3,6] - [[1,2,3],[1,2,3],[1,2,3,4,5,6]]
Thanks in advance.
You could use map method.
var arr = [3, 6];
print(arr.map { Array(1...$0) })
Output
[[1, 2, 3], [1, 2, 3, 4, 5, 6]]
I simplified my code as much as I could to make it still be a reproducible example.
When I use contains like this in a chain of calls it does compile, work and contains accepts nil when it shouldn't, I think.
let array = [1, 2, 3, 4, 5].filter { _ in
[1, 2, 3].map { smallNumber in
"\(smallNumber)"
}
.contains(nil)
}
But when I assign map result to a variable and then call contains with nil value the code doesn't even compile.
let array = [1, 2, 3, 4, 5].filter { _ in
let mappedNumbers = [1, 2, 3].map { smallNumber in
"\(smallNumber)"
}
return mappedNumbers.contains(nil)
}
Xcode is complaining about 'nil' is not compatible with expected argument type 'String', that is right.
I expect the same error in the first example.
The compiler can automatically wrap a value into an optional, if required by the context. That is what makes simple assignments like
let value: Int? = 123
possible. In your first example, the return type of the closure is inferred as String? from the context, so that the map returns [String?], and .contains(nil) can be applied to it. I.e. the compiler understands the code as
let array = [1, 2, 3, 4, 5].filter { _ in
[1, 2, 3].map { smallNumber -> String? in
"\(smallNumber)"
}
.contains(nil)
}
In the second example the compiler does not have that context, and mappedNumbers has the type [String]. You can make it compile by specifying the closure return type String? explicitly:
let array = [1, 2, 3, 4, 5].filter { _ in
let mappedNumbers = [1, 2, 3].map { smallNumber -> String? in
"\(smallNumber)"
}
return mappedNumbers.contains(nil)
}
Hello everyone I need help. I have JSON with dynamic array dimension value. This is the example :
//array 1 dimension
"array_dimension" : 1, //we can change to 2 dimension or more
"my_array" : [0, 1, 2, 3, 4] //the value adjust with array_dimension
//array 2 dimension
"array_dimension" : 2,
"my_array" : [[0, 1, 2], [3, 4], [5]]
//array 3 dimension
"array_dimension" : 3,
"my_array" : [[[0, 1], [2]], [[3], [4]], [[5]]]
And now I only can catch the my_array value in variable with static array dimension like this :
//example value in array 2 dimension
"array_dimension" : 2,
"my_array" : [[0, 1, 2], [3, 4], [5]]
//Program to catch my_array value in Swift 3
if let my_array = myJSON["my_array"] as? [[Int]] {
var myArray: [[Int]]?
myArray = my_array
} else {
print("\(TAG) error : JSON parsing my_array not found")
}
How can I catch all dynamic array dimension from my_array value in a variable (Swift 3) ?
UPDATE :
How I can use that technique ?
Your array is not Array<Int>, your array is Array<Any>.
Inside application you know how deep arrays in your root array. Based on that, you can take "last" meta array, that contains Int values (with type Array<Any>). After that you can get element by index and use:
let value : Int = Null;
if let intElement = array[index] as? Int {
value = intElement;
}
else
{
print("Error with element type (print element)");
}
I create a dictionary in Swift:
var type:String
var content:[UInt8]
let dict = NSMutableDictionary()
dict.setValue(type, forKey: "type")
dict.setValue(content, forKey: "content")
I get an error: Cannot convert value of type [UInt8] to expected argument type 'AnyObject?', but if I change the content type as [UInt], it will work fine. Why?
In fact, I want to define a byte array as in Java, so I want to use [UInt8], anyone could help me?
you can use Swift native types
var dict: Dictionary<String,Array<UInt8>> = [:]
dict["first"]=[1,2,3]
print(dict) // ["first": [1, 2, 3]]
i recommend you to use native Swift type as much as you can ... Please, see Martins's notes to you question, it is very useful!
if the case is you want to store there any value, just define you dictionary as the proper type
var dict: Dictionary<String,Array<Any>> = [:]
dict["first"]=[1,2,3]
class C {
}
dict["second"] = ["alfa", Int(1), UInt(1), C()]
print(dict) // ["first": [1, 2, 3], "second": ["alfa", 1, 1, C]]
to see, that the type of the value is still well known, you can check it
dict["second"]?.forEach({ (element) -> () in
print(element, element.dynamicType)
})
/*
alfa String
1 Int
1 UInt
C C
*/
if you want to store Any value, you are free to do it ...
var type:String = "test"
var content:[UInt8] = [1,2,3,4]
var dict: Dictionary<String,Any> = [:]
dict["type"] = type
dict["content"] = content
dict.forEach { (element) -> () in // ["content": [1, 2, 3, 4], "type": "test"]
print("key:", element.0, "value:", element.1, "with type:", element.1.dynamicType)
/*
key: content value: [1, 2, 3, 4] with type: Array<UInt8>
key: type value: test with type: String
*/
}
I have recently found a source code in swift and I am trying to get it to objective-C. The one thing I was unable to understand is this:
var theData:UInt8!
theData = 3;
NSData(bytes: [theData] as [UInt8], length: 1)
Can anybody help me with the Obj-C equivalent?
Just to give you some context, I need to send UInt8 to a CoreBluetooth peripheral (CBPeripheral) as UInt8. Float or integer won't work because the data type would be too big.
If you write the Swift code slightly simpler as
var theData : UInt8 = 3
let data = NSData(bytes: &theData, length: 1)
then it is relatively straight-forward to translate that to Objective-C:
uint8_t theData = 3;
NSData *data = [NSData dataWithBytes:&theData length:1];
For multiple bytes you would use an array
var theData : [UInt8] = [ 3, 4, 5 ]
let data = NSData(bytes: &theData, length: theData.count)
which translates to Objective-C as
uint8_t theData[] = { 3, 4, 5 };
NSData *data = [NSData dataWithBytes:&theData length:sizeof(theData)];
(and you can omit the address-of operator in the last statement,
see for example How come an array's address is equal to its value in C?).
In Swift 3
var myValue: UInt8 = 3 // This can't be let properties
let value = Data(bytes: &myValue, count: MemoryLayout<UInt8>.size)
In Swift,
Data has a native init method.
// Foundation -> Data
/// Creates a new instance of a collection containing the elements of a
/// sequence.
///
/// - Parameter elements: The sequence of elements for the new collection.
/// `elements` must be finite.
#inlinable public init<S>(_ elements: S) where S : Sequence, S.Element == UInt8
#available(swift 4.2)
#available(swift, deprecated: 5, message: "use `init(_:)` instead")
public init<S>(bytes elements: S) where S : Sequence, S.Element == UInt8
So, the following will work.
let values: [UInt8] = [1, 2, 3, 4]
let data = Data(values)