问题描述:

Currently trying to learn swift and I am a bit confused to why some arguments are written with a dot before it and some don't. For example

To add a button to a UIAlertView object

alert's name = simpleAlert

buttons title = "YES"

button's style = Default

handler = nil

why is the appropriate way to write this is

simpleAlert.addAction(UIAlertAction(title:"YES",style: .Default, handler: nil))

instead of

simpleAlert.addAction(UIAlertAction(title:"YES",style: Default, handler: nil))

网友答案:

It's a short way of writing UIAlertActionStyle.Default (UIAlertActionStyle being an enum and Default being a value of it). The UIAlertView already knows you are gonna use a UIAlertActionStyle for that parameter so you can just write that enum's value.

网友答案:
simpleAlert.addAction(UIAlertAction(title:"YES",style: .Default, handler: nil))

can also be written as a

 simpleAlert.addAction(UIAlertAction(title:"YES",style: UIAlertActionStyle.Default
, handler: nil))

UIAlertActionStyle is the Enum

enum UIAlertActionStyle : Int {

    case Default
    case Cancel
    case Destructive
}

so .Default is just a simplification which means Enum type is Already given we just have to pass the proper case which we want to use.

网友答案:

As others have already said, that is a shorthand for UIAlertActionStyle.Default.

Skipping the name of the enum and simply listing the value (.Default instead of UIAlertActionStyle.Default) is an example of Swift "type inference".

Type inference means that if the compiler can infer (figure out) the type of some value/parameter, you don't have to state it explicitly. In the example above, the value you provide for style must be a value of type UIAlertActionStyle, so you can skip that part.

相关阅读:
Top