Tìm hiểu các loại keyword trong Swift:
Keywords Using #
#available : Kiểm tra điều kiện lúc runtime, tính khả dụng ví dụ như kiểm tra version ios.
if #available(iOS 13, *)
{
print("iOS 13 APIs are available")
}
#colorLiteral : ra bộ chọn màu.
let aColor = #colorLiteral //Brings up color picker
#column : Biết mình đang ở cột nào.
class Person
{
func printInfo()
{
print("Some person info - on column \(#column)")
}
}
let aPerson = Person()
aPerson.printInfo() //Some person info - on column 53
#if #elseif #else #endif : Kiểm tra điều kiện như là đang xài hệ điều hành nào, version bao nhiêu…
#if os(iOS)
print("Compiled for an iOS device")
#elseif os(macOS)
print("Compiled on a mac computer")
#endif
#file : Trả về tên file chứa nó.
class Person
{
func printInfo()
{
print("Some person info - inside file \(#file)")
}
}
let aPerson = Person()
aPerson.printInfo() //Some person info - inside file /*file path to the Playground file I wrote it in*/
#function: trả về tên của function chứa nó, trong getter, setter thì sẽ trả về tên thuộc tính, trong 1 số hàm như init hoặc subscript thì sẽ trả về tên của từ khoá đó, nếu đặt ở ngay đầu file thì sẽ trả về tên của module hiện tại.
class Person
{
func printInfo()
{
print("Some person info - inside function \(#function)")
}
}
let aPerson = Person()
aPerson.printInfo() //Some person info - inside function printInfo()
#imageLiteral: show nguyên kho hình lên cho mình chọn.
let anImage = #imageLiteral //Brings up a picker to select an image inside the playground file
#line : Trả về số dòng hiện tại.
class Person
{
func printInfo()
{
print("Some person info - on line number \(#line)")
}
}let aPerson = Person()
aPerson.printInfo() //Some person info - on line number 5
#selector : dễ hiểu là đảm bảo hàm nào đó tồn tại và gắn vào 1 action nào đó.
//Static checking occurs to make sure doAnObjCMethod exists
control.sendAction(#selector(doAnObjCMethod), to: target, forEvent: event)
#sourceLocation : gọi dòng này xong là reset số dòng với tên file, không còn đúng như trước lúc gọi.
#sourceLocation(file:"foo.swift", line:6)//Reports new values
print(#file)
print(#line)//This resets the source code location back to the default values numbering and filename
#sourceLocation()print(#file)
print(#line)
@objc: hàm kế thừa objective-C
@objc func runTimer(){
print("1")
}
@avaiable: kiểm tra điều kiện lúc runtime, tính khả dụng nhưng đặt ngoài class thì dùng @
@available(iOS 13.0, *)
class AppDelegate: UIResponder, UIApplicationDelegate {
...
}
Bình luận