What are 3 items in a Swift method parameter for?
This is how Swift mimics Objective C's named parameters (pseudo naming of arguments). Its pretty easy to break down.
mutating func moveByX(deltaX: Double, y deltaY: Double)
1 2 3 4 5 6
- Beginning of method name
- First parameter name
- First parameter type
- Second part of method name
- Second parameter name
- Second parameter type
In this example, the method is actually called moveByX:y:
The equivalent Objective C method definition would look like this.
- (void)moveByX:(Double)deltaX y:(Double)deltaY
When calling this method, the second part of the name is included alone with the rest of the arguments.
var dub = Double(0.5)
moveByX(dub, y: dub)
Swift 3 Function Parameter (Dictionary - Array)
It looks like formValues
is of type Dictionary
not Array
. Change your upload function parameters to this:
func upload(parameters: [String: Any?]) {
print(parameters);
}
Using Function Parameter Names in Swift
This is to follow an convention we were all used to from Objective-C, where the name of the first parameter is combined with the method name. Here's an example:
- (void)incrementByAmount:(NSInteger)amount
numberOfTimes:(NSInteger)times
{
// stuff
}
You could call the method like:
[self incrementByAmount:2 numberOfTimes:7];
And it feels more natural to read by incorporating the name of the parameter into the method's name. In Swift, you can achieve the same with the following:
func incrementByAmount(amount: Int, numberOfTimes: Int) {
// same stuff in Swift
}
And call the method like:
incrementByAmount(2, numberOfTimes: 7)
If you don't want to use this convention, Swift gives you the ability to be more explicit and define separate internal and external parameter names, like so:
func incrementByAmount(incrementBy amount: Int, numberOfTimes: Int) {
// same stuff in Swift
// access `amount` at this scope.
}
You can call the method like this:
incrementByAmount(incrementBy: 2, numberOfTimes: 7)
How to pass a Type as a parameter in Swift
I think this should work:
func getObjectsThatConformToType<T>(type:T.Type) -> [T]{
var returnArray: [T] = []
for(myKey, myValue) in allCreatedObjects{
if let comformantModule = myValue as? T {
returnArray.append(comformantModule)
}
}
return returnArray
}
How can I pass in any function as a parameter?
If you use a Set and make it Hashable instead of Comparable, it's fairly straightforward
extension Array {
func mapThenUnique<T: Hashable>(f: (Element) -> T) -> [T] {
var seen = Set<T>()
return map { f($0) }.filter { seen.insert($0).inserted }
}
}
["abc", "Hi", "AbC"].mapThenUnique { $0.lowercased() } // ["abc", "hi"]
[2, 9, -9, 3].mapThenUnique { Int($0) * $0 } // [4, 81, 9]
Or if you don't care about the original order
Set(["abc", "Hi", "AbC"].map { $0.lowercased() }) // ["abc", "hi"] or ["hi", "abc"]
Set([2, 9, -9, 3].map { Int($0) * $0 }) // Some random order of [4, 81, 9]
Also a more "correct" way to do this in Swift would be to create the extension on Collection
extension Collection where Element: Hashable {
func mapThenUnique(f: (Element) -> Element) -> [Element] {
var seen = Set<Element>()
return map { f($0) }.filter { seen.insert($0).inserted }
}
}
Although I consider it "bad form" to have a function that does two things, so my personal preference would be
extension Collection where Element: Hashable {
func unique() -> [Element] {
var seen = Set<Element>()
return filter { seen.insert($0).inserted }
}
}
["abc", "Hi", "AbC"].map { $0.lowercased() }.unique()
(Again, assuming you want to keep the order. Otherwise, just use a Set!)
POST Parameters in Swift
Try to do parameter as array.
var params=[Candto] ()
Then loop whenever you want and append your object to array.
pass a dictionary item as a parameter
I am not sure exactly what you want to pass to the other function but you should use the function randomElement()
girlsName.randomElement() // a random key/value pair
girlsName.keys.randomElement() // a random key
girlsName.values.randomElement() // a random value
So if you want to pass a name (value) it could look like
submite(randomVal: girlsName.values.randomElement() ?? "")
if submite
is declared as
func submite(randomVal: String)
Swift - How to use a class type as a parameter / variable
First read Metatype Type in the The Swift Programming Language. Once read continue with the answer.
From that you have learnt that you can declare a function parameter's type to be the type of types (you are allowed to go crosseyed), AKA metatype, and can therefore pass a type to a function. Combine that with generics and Swift's type inference and you could declare your function as:
func sortFileArrayByType<T>(fileAttributeKeyString : String,
attributeType : T.Type,
fileURLArray : [URL]
) -> [(url: URL, attribute: T)]
where T : Comparable
This adds the parameter attributeType
whose type is the metatype of T
where T
will be inferred. For example the metatype String.self
could be passed and T
will be inferred to be String
.
The where
clause constrains T
so that only types which are Comparable
are allowed, this is required to enable the function to do sorting. File attributes can be Date
, String
and NSNumber
valued; unfortunately the latter does not conform to Comparable
so you need to add an extension to make it, the following will suffice:
extension NSNumber : Comparable
{
public static func <(a : NSNumber, b : NSNumber) -> Bool { return a.compare(b) == .orderedAscending }
public static func ==(a : NSNumber, b : NSNumber) -> Bool { return a.compare(b) == .orderedSame }
}
Within the body of the function you need to declare your array of tuples to have attributes of type T
:
var tupleArrayWithURLandAttribute : [(url: URL, attribute: T)] = []
and when you add entries you need to cast the value returned by attributesOfItem
to be T
:
tupleArrayWithURLandAttribute.append((url: url, attribute: value as! T))
Note the use of as!
here, you must match the attribute name and the type of its value correctly in the function call or you will get a runtime abort. Handling this as a soft error, if needed, is left as an exercise.
There are a number of typos etc. in the code you posted, they are left for you to fix, having done that your function should work. A call might look like:
let ans = sortFileArrayByType2(fileAttributeKeyString: "NSFileCreationDate",
attributeType: Date.self,
fileURLArray: urlArray)
and the type of ans
in this case will be [(url: URL, attribute: Date)]
HTH
Related Topics
Getch() Equivalent in Swift: Read a Single Character from Stdin Without a Newline
Is There a Neat Way to Represent a Fraction as an Attributed String
Initializer for Conditional Binding Must Have Optional Type, Not '[String:Any]'
Behavior of the Cameranode Is Unclear When Moving a 3D Model in a Scene with Scenekit
Fetch an Email Body in Mailcore2 Osx with Swift
Stateobject as Parameter for Another Object in Init()
What Is the Shortest Way to Run Same Code N Times in Swift
Color Text of Status Bar in Xcode 6-B3 (Swift)
C++ Dylib in Swift Project - Undefined Symbols for Function Exposed in Dylib
Exc_Bad_Instruction Only in iPhone 5 Simulator
Elegant 'Bounded' Methodology in Swift
Swift 3 Errors with Additional Data
Testing If Double from Textfield Has a Value or Not
Decode/Encode Dictionary Keyed by Date
Implementing a 'Report' Feature for Inappropriate Content Swift Firebase