repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Bing0/ThroughWall | ThroughWall/iCloudSyncViewController.swift | 1 | 8430 | //
// iCloudSyncViewController.swift
// ThroughWall
//
// Created by Bingo on 05/08/2017.
// Copyright © 2017 Wu Bin. All rights reserved.
//
import UIKit
class iCloudSyncViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
setTopArear()
tableView.tableFooterView = UIView()
tableView.backgroundColor = veryLightGrayUIColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
func setTopArear() {
navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
navigationController?.navigationBar.tintColor = UIColor.white
navigationController?.navigationBar.isTranslucent = false
navigationController?.navigationBar.setBackgroundImage(image(fromColor: topUIColor), for: .any, barMetrics: .default)
navigationController?.navigationBar.shadowImage = UIImage()
self.navigationItem.title = "iCloud Sync Setting"
}
func image(fromColor color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(color.cgColor)
context?.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsGetCurrentContext()
return image!
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
return 2
}
return 3
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return " Sync Server"
case 1:
return " Sync Rule Configs"
default:
return nil
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let _ = self.tableView(tableView, titleForHeaderInSection: section) {
return 60
}
return 40
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if let header = self.tableView(tableView, titleForHeaderInSection: section) {
//global mode section
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 18))
let label = UILabel(frame: CGRect(x: 10, y: 35, width: tableView.frame.width, height: 20))
label.text = header
label.textColor = UIColor.gray
label.font = UIFont.boldSystemFont(ofSize: 16)
view.backgroundColor = veryLightGrayUIColor
view.addSubview(label)
return view
} else {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 18))
view.backgroundColor = veryLightGrayUIColor
return view
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
if let lastSyncTime = UserDefaults().value(forKey: kLastServerSyncTime) as? String {
let cell = tableView.dequeueReusableCell(withIdentifier: "subtitleCell", for: indexPath)
cell.textLabel?.text = "Sync with iCloud"
cell.detailTextLabel?.text = lastSyncTime
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
cell.textLabel?.text = "Sync with iCloud"
return cell
}
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
cell.textLabel?.text = "Delete iCloud Servers"
return cell
default:
break
}
case 1:
switch indexPath.row {
case 0:
if let lastSyncTime = UserDefaults().value(forKey: kLastServerSyncTime) as? String {
let cell = tableView.dequeueReusableCell(withIdentifier: "subtitleCell", for: indexPath)
cell.textLabel?.text = "Update to iCloud"
cell.detailTextLabel?.text = lastSyncTime
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
cell.textLabel?.text = "Update to iCloud"
return cell
}
case 1:
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
cell.textLabel?.text = "Download from iCloud"
return cell
case 2:
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
cell.textLabel?.text = "Clear from iCloud"
return cell
default:
break
}
default:
break
}
let cell = tableView.dequeueReusableCell(withIdentifier: "basicCell", for: indexPath)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
syncServersWithiCloud()
case 1:
clearServersFromiCloud()
default:
break
}
case 1:
break
default:
break
}
}
func syncServersWithiCloud() {
//get local
// let serverContent = SiteConfigController().readSiteConfigsContent()
// let servers = serverContent.components(separatedBy: "#\n")
//download
//compare
//upload
// for server in servers {
// var items = server.components(separatedBy: "\n")
// for item in items {
// if item
// }
// }
}
func uploadServerToiCloud(withContent content: String) {
CloudController().saveNewServerToiCloud(withContent: content) { (recordName, creationDate, error) in
if let error = error {
let alertController = UIAlertController(title: "Error", message: "Save server to iCloud failed with error: \(error)", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
})
alertController.addAction(action)
self.present(alertController, animated: true, completion: nil)
}
}
}
func clearServersFromiCloud() {
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | d53b6df8a9e4f5a7c2519bdaf70ff702 | 34.868085 | 157 | 0.595682 | 5.469825 | false | false | false | false |
victorchee/CollectionView | BookCollectionView/BookCollectionView/BookPageCell.swift | 2 | 3639 | //
// BookPageCell.swift
// BookCollectionView
//
// Created by qihaijun on 11/30/15.
// Copyright © 2015 VictorChee. All rights reserved.
//
import UIKit
class BookPageCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
var book: Book?
var isRightPage = false
var shadowLayer = CAGradientLayer()
override var bounds: CGRect {
didSet {
shadowLayer.frame = bounds
}
}
var image: UIImage? {
didSet {
let corners: UIRectCorner = isRightPage ? [.topRight, .bottomRight] : [.topLeft, .bottomLeft]
imageView.image = image?.imageByScalingAndCroppingForSize(bounds.size).imageWithRoundedCornersSize(20, corners: corners)
}
}
override func awakeFromNib() {
super.awakeFromNib()
setupAntialiasing()
initShadowLayer()
}
fileprivate func setupAntialiasing() {
layer.allowsEdgeAntialiasing = true
imageView.layer.allowsEdgeAntialiasing = true
}
fileprivate func initShadowLayer() {
shadowLayer = CAGradientLayer()
shadowLayer.frame = bounds
shadowLayer.startPoint = CGPoint(x: 0, y: 0.5)
shadowLayer.endPoint = CGPoint(x: 1, y: 0.5)
imageView.layer.addSublayer(shadowLayer)
}
fileprivate func getRatioFromTransform() -> CGFloat {
var ratio: CGFloat = 0
if let rotationYValue = layer.value(forKey: "transform.rotation.y") {
let rotationY = CGFloat((rotationYValue as AnyObject).floatValue)
if isRightPage {
ratio = 1 - rotationY / CGFloat(-M_PI_2)
} else {
ratio = -(1 - rotationY / CGFloat(M_PI_2))
}
}
return ratio
}
func updateShadowLayer(animated: Bool = false) {
let ratio: CGFloat = getRatioFromTransform()
let inverseRatio = 1 - abs(ratio)
if !animated {
CATransaction.begin()
CATransaction.setDisableActions(!animated)
}
if isRightPage {
shadowLayer.colors = [UIColor.darkGray.withAlphaComponent(inverseRatio * 0.45).cgColor,
UIColor.darkGray.withAlphaComponent(inverseRatio * 0.40).cgColor,
UIColor.darkGray.withAlphaComponent(inverseRatio * 0.55).cgColor]
shadowLayer.locations = [NSNumber(value: 0 as Float), NSNumber(value: 0.02 as Float), NSNumber(value: 1.0 as Float)];
} else {
shadowLayer.colors = [UIColor.darkGray.withAlphaComponent(inverseRatio * 0.30).cgColor,
UIColor.darkGray.withAlphaComponent(inverseRatio * 0.40).cgColor,
UIColor.darkGray.withAlphaComponent(inverseRatio * 0.50).cgColor,
UIColor.darkGray.withAlphaComponent(inverseRatio * 0.55).cgColor]
shadowLayer.locations = [NSNumber(value: 0 as Float), NSNumber(value: 0.50 as Float), NSNumber(value: 0.98 as Float), NSNumber(value: 1.0 as Float)];
}
if !animated {
CATransaction.commit()
}
}
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes.copy() as! UICollectionViewLayoutAttributes)
if layoutAttributes.indexPath.item % 2 == 0 {
layer.anchorPoint = CGPoint(x: 0, y: 0.5)
isRightPage = true
} else {
layer.anchorPoint = CGPoint(x: 1, y: 0.5)
isRightPage = false
}
// updateShadowLayer()
}
}
| mit | 43bceb3aef80ecf21f1f8a5be1df9408 | 33.980769 | 161 | 0.606927 | 4.793149 | false | false | false | false |
zshannon/SwiftForms | SwiftFormsApplication/ExampleFormViewController.swift | 1 | 8803 | //
// ExampleFormViewController.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import UIKit
import SwiftForms
class ExampleFormViewController: FormViewController {
struct Static {
static let nameTag = "name"
static let passwordTag = "password"
static let lastNameTag = "lastName"
static let jobTag = "job"
static let speciesTag = "species"
static let emailTag = "email"
static let URLTag = "url"
static let phoneTag = "phone"
static let enabled = "enabled"
static let check = "check"
static let segmented = "segmented"
static let picker = "picker"
static let birthday = "birthday"
static let categories = "categories"
static let button = "button"
static let stepper = "stepper"
static let slider = "slider"
static let textView = "textview"
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.loadForm()
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Submit", style: .Plain, target: self, action: "submit:")
}
/// MARK: Actions
func submit(_: UIBarButtonItem!) {
let message = self.form.formValues().description
let alert: UIAlertView = UIAlertView(title: "Form output", message: message, delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
/// MARK: Private interface
private func loadForm() {
let form = FormDescriptor()
form.title = "Example Form"
let section1 = FormSectionDescriptor()
var row: FormRowDescriptor! = FormRowDescriptor(tag: Static.emailTag, rowType: .Email, title: "Email")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "[email protected]", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section1.addRow(row)
row = FormRowDescriptor(tag: Static.passwordTag, rowType: .Password, title: "Password")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "Enter password", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section1.addRow(row)
let section2 = FormSectionDescriptor()
row = FormRowDescriptor(tag: Static.nameTag, rowType: .Name, title: "First Name")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. Miguel Ángel", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section2.addRow(row)
row = FormRowDescriptor(tag: Static.lastNameTag, rowType: .Name, title: "Last Name")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. Ortuño", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section2.addRow(row)
row = FormRowDescriptor(tag: Static.jobTag, rowType: .Text, title: "Job")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. Entrepreneur", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section2.addRow(row)
row = FormRowDescriptor(tag: Static.speciesTag, rowType: .Text, title: "Species (Read-Only)")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. Human", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
row.configuration[FormRowDescriptor.Configuration.ReadOnly] = true
row.value = "Human"
section2.addRow(row)
let section3 = FormSectionDescriptor()
row = FormRowDescriptor(tag: Static.URLTag, rowType: .URL, title: "URL")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. gethooksapp.com", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section3.addRow(row)
row = FormRowDescriptor(tag: Static.phoneTag, rowType: .Phone, title: "Phone")
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.placeholder" : "e.g. 0034666777999", "textField.textAlignment" : NSTextAlignment.Right.rawValue]
section3.addRow(row)
let section4 = FormSectionDescriptor()
row = FormRowDescriptor(tag: Static.enabled, rowType: .BooleanSwitch, title: "Enable")
section4.addRow(row)
row = FormRowDescriptor(tag: Static.check, rowType: .BooleanCheck, title: "Doable")
section4.addRow(row)
row = FormRowDescriptor(tag: Static.segmented, rowType: .SegmentedControl, title: "Priority")
row.configuration[FormRowDescriptor.Configuration.Options] = [0, 1, 2, 3]
row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in
switch( value ) {
case 0:
return "None"
case 1:
return "!"
case 2:
return "!!"
case 3:
return "!!!"
default:
return nil
}
} as TitleFormatterClosure
row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["titleLabel.font" : UIFont.boldSystemFontOfSize(30.0), "segmentedControl.tintColor" : UIColor.redColor()]
section4.addRow(row)
section4.headerTitle = "An example header title"
section4.footerTitle = "An example footer title"
let section5 = FormSectionDescriptor()
row = FormRowDescriptor(tag: Static.picker, rowType: .Picker, title: "Gender")
row.configuration[FormRowDescriptor.Configuration.Options] = ["F", "M", "U"]
row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in
switch( value ) {
case "F":
return "Female"
case "M":
return "Male"
case "U":
return "I'd rather not to say"
default:
return nil
}
} as TitleFormatterClosure
row.value = "M"
section5.addRow(row)
row = FormRowDescriptor(tag: Static.birthday, rowType: .Date, title: "Birthday")
section5.addRow(row)
row = FormRowDescriptor(tag: Static.categories, rowType: .MultipleSelector, title: "Categories")
row.configuration[FormRowDescriptor.Configuration.Options] = [0, 1, 2, 3, 4]
row.configuration[FormRowDescriptor.Configuration.AllowsMultipleSelection] = true
row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in
switch( value ) {
case 0:
return "Restaurant"
case 1:
return "Pub"
case 2:
return "Shop"
case 3:
return "Hotel"
case 4:
return "Camping"
default:
return nil
}
} as TitleFormatterClosure
section5.addRow(row)
let section6 = FormSectionDescriptor()
section6.headerTitle = "Stepper & Slider"
row = FormRowDescriptor(tag: Static.stepper, rowType: .Stepper, title: "Step count")
row.configuration[FormRowDescriptor.Configuration.MaximumValue] = 200.0
row.configuration[FormRowDescriptor.Configuration.MinimumValue] = 20.0
row.configuration[FormRowDescriptor.Configuration.Steps] = 2.0
section6.addRow(row)
row = FormRowDescriptor(tag: Static.slider, rowType: .Slider, title: "Slider")
row.value = 0.5
section6.addRow(row)
let section7 = FormSectionDescriptor()
row = FormRowDescriptor(tag: Static.textView, rowType: .MultilineText, title: "Notes")
section7.headerTitle = "Multiline TextView"
section7.addRow(row)
let section8 = FormSectionDescriptor()
row = FormRowDescriptor(tag: Static.button, rowType: .Button, title: "Dismiss")
row.configuration[FormRowDescriptor.Configuration.DidSelectClosure] = {
self.view.endEditing(true)
} as DidSelectClosure
section8.addRow(row)
form.sections = [section1, section2, section3, section4, section5, section6, section7, section8]
self.form = form
}
}
| mit | abcff285f1e04f7760d6034b2abb1307 | 40.706161 | 189 | 0.626818 | 4.853833 | false | true | false | false |
Acidburn0zzz/firefox-ios | Client/Frontend/Browser/LoginsHelper.swift | 1 | 10431 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import Storage
import XCGLogger
import WebKit
import SwiftyJSON
private let log = Logger.browserLogger
class LoginsHelper: TabContentScript {
fileprivate weak var tab: Tab?
fileprivate let profile: Profile
fileprivate var snackBar: SnackBar?
// Exposed for mocking purposes
var logins: RustLogins {
return profile.logins
}
class func name() -> String {
return "LoginsHelper"
}
required init(tab: Tab, profile: Profile) {
self.tab = tab
self.profile = profile
}
func scriptMessageHandlerName() -> String? {
return "loginsManagerMessageHandler"
}
fileprivate func getOrigin(_ uriString: String, allowJS: Bool = false) -> String? {
guard let uri = URL(string: uriString),
let scheme = uri.scheme, !scheme.isEmpty,
let host = uri.host else {
// bug 159484 - disallow url types that don't support a hostPort.
// (although we handle "javascript:..." as a special case above.)
log.debug("Couldn't parse origin for \(uriString)")
return nil
}
if allowJS && scheme == "javascript" {
return "javascript:"
}
var realm = "\(scheme)://\(host)"
// If the URI explicitly specified a port, only include it when
// it's not the default. (We never want "http://foo.com:80")
if let port = uri.port {
realm += ":\(port)"
}
return realm
}
func loginRecordFromScript(_ script: [String: Any], url: URL) -> LoginRecord? {
guard let username = script["username"] as? String,
let password = script["password"] as? String,
let origin = getOrigin(url.absoluteString) else {
return nil
}
var dict: [String: Any] = [
"hostname": origin,
"username": username,
"password": password
]
if let string = script["formSubmitURL"] as? String,
let formSubmitURL = getOrigin(string) {
dict["formSubmitURL"] = formSubmitURL
}
if let passwordField = script["passwordField"] as? String {
dict["passwordField"] = passwordField
}
if let usernameField = script["usernameField"] as? String {
dict["usernameField"] = usernameField
}
return LoginRecord(fromJSONDict: dict)
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
guard let res = message.body as? [String: Any],
let type = res["type"] as? String else {
return
}
// We don't use the WKWebView's URL since the page can spoof the URL by using document.location
// right before requesting login data. See bug 1194567 for more context.
if let url = message.frameInfo.request.url {
// Since responses go to the main frame, make sure we only listen for main frame requests
// to avoid XSS attacks.
if message.frameInfo.isMainFrame && type == "request" {
requestLogins(res, url: url)
} else if type == "submit" {
if profile.prefs.boolForKey("saveLogins") ?? true {
if let login = loginRecordFromScript(res, url: url) {
setCredentials(login)
}
}
}
}
}
class func replace(_ base: String, keys: [String], replacements: [String]) -> NSMutableAttributedString {
var ranges = [NSRange]()
var string = base
for (index, key) in keys.enumerated() {
let replace = replacements[index]
let range = string.range(of: key,
options: .literal,
range: nil,
locale: nil)!
string.replaceSubrange(range, with: replace)
let nsRange = NSRange(location: string.distance(from: string.startIndex, to: range.lowerBound),
length: replace.count)
ranges.append(nsRange)
}
var attributes = [NSAttributedString.Key: AnyObject]()
attributes[NSAttributedString.Key.font] = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)
attributes[NSAttributedString.Key.foregroundColor] = UIColor.Photon.Grey60
let attr = NSMutableAttributedString(string: string, attributes: attributes)
let font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)
for range in ranges {
attr.addAttribute(NSAttributedString.Key.font, value: font, range: range)
}
return attr
}
func setCredentials(_ login: LoginRecord) {
if login.password.isEmpty {
log.debug("Empty password")
return
}
profile.logins
.getLoginsForProtectionSpace(login.protectionSpace, withUsername: login.username)
.uponQueue(.main) { res in
if let data = res.successValue {
log.debug("Found \(data.count) logins.")
for saved in data {
if let saved = saved {
if saved.password == login.password {
_ = self.profile.logins.use(login: saved)
return
}
self.promptUpdateFromLogin(login: saved, toLogin: login)
return
}
}
}
self.promptSave(login)
}
}
fileprivate func promptSave(_ login: LoginRecord) {
guard login.isValid.isSuccess else {
return
}
let promptMessage: String
let https = "^https:\\/\\/"
let url = login.hostname.replacingOccurrences(of: https, with: "", options: .regularExpression, range: nil)
let userName = login.username
if !userName.isEmpty {
promptMessage = String(format: Strings.SaveLoginUsernamePrompt, userName, url)
} else {
promptMessage = String(format: Strings.SaveLoginPrompt, url)
}
if let existingPrompt = self.snackBar {
tab?.removeSnackbar(existingPrompt)
}
snackBar = TimerSnackBar(text: promptMessage, img: UIImage(named: "key"))
let dontSave = SnackButton(title: Strings.LoginsHelperDontSaveButtonTitle, accessibilityIdentifier: "SaveLoginPrompt.dontSaveButton", bold: false) { bar in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
return
}
let save = SnackButton(title: Strings.LoginsHelperSaveLoginButtonTitle, accessibilityIdentifier: "SaveLoginPrompt.saveLoginButton", bold: true) { bar in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
_ = self.profile.logins.add(login: login)
LeanPlumClient.shared.track(event: .savedLoginAndPassword)
}
snackBar?.addButton(dontSave)
snackBar?.addButton(save)
tab?.addSnackbar(snackBar!)
}
fileprivate func promptUpdateFromLogin(login old: LoginRecord, toLogin new: LoginRecord) {
guard new.isValid.isSuccess else {
return
}
new.id = old.id
let formatted: String
let userName = new.username
if !userName.isEmpty {
formatted = String(format: Strings.UpdateLoginUsernamePrompt, userName, new.hostname)
} else {
formatted = String(format: Strings.UpdateLoginPrompt, new.hostname)
}
if let existingPrompt = self.snackBar {
tab?.removeSnackbar(existingPrompt)
}
snackBar = TimerSnackBar(text: formatted, img: UIImage(named: "key"))
let dontSave = SnackButton(title: Strings.LoginsHelperDontUpdateButtonTitle, accessibilityIdentifier: "UpdateLoginPrompt.donttUpdateButton", bold: false) { bar in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
}
let update = SnackButton(title: Strings.LoginsHelperUpdateButtonTitle, accessibilityIdentifier: "UpdateLoginPrompt.updateButton", bold: true) { bar in
self.tab?.removeSnackbar(bar)
self.snackBar = nil
_ = self.profile.logins.update(login: new)
}
snackBar?.addButton(dontSave)
snackBar?.addButton(update)
tab?.addSnackbar(snackBar!)
}
fileprivate func requestLogins(_ request: [String: Any], url: URL) {
guard let requestId = request["requestId"] as? String,
// Even though we don't currently use these two fields,
// verify that they were received as additional confirmation
// that this is a valid request from LoginsHelper.js.
let _ = request["formOrigin"] as? String,
let _ = request["actionOrigin"] as? String,
// We pass in the webview's URL and derive the origin here
// to workaround Bug 1194567.
let origin = getOrigin(url.absoluteString) else {
return
}
let protectionSpace = URLProtectionSpace.fromOrigin(origin)
profile.logins.getLoginsForProtectionSpace(protectionSpace).uponQueue(.main) { res in
guard let cursor = res.successValue else {
return
}
let logins: [[String: Any]] = cursor.compactMap { login in
// `requestLogins` is for webpage forms, not for HTTP Auth, and the latter has httpRealm != nil; filter those out.
return login?.httpRealm == nil ? login?.toJSONDict() : nil
}
log.debug("Found \(logins.count) logins.")
let dict: [String: Any] = [
"requestId": requestId,
"name": "RemoteLogins:loginsFound",
"logins": logins
]
let json = JSON(dict)
let injectJavaScript = "window.__firefox__.logins.inject(\(json.stringify()!))"
self.tab?.webView?.evaluateJavascriptInDefaultContentWorld(injectJavaScript)
}
}
}
| mpl-2.0 | 36ee4525249211602be0d99a02a12019 | 36.65704 | 170 | 0.590356 | 4.983755 | false | false | false | false |
dawsonbotsford/MobileAppsFall2015 | iOS/gestures/gestures/ViewController.swift | 1 | 2402 | //
// ViewController.swift
// gestures
//
// Created by Dawson Botsford on 10/13/15.
// Copyright © 2015 Dawson Botsford. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UIGestureRecognizerDelegate {
@IBAction func handlePan(sender: UIPanGestureRecognizer) {
let translation = sender.translationInView(view)
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y)
sender.setTranslation(CGPointZero, inView: view)
if sender.state == UIGestureRecognizerState.Ended {
let velocity = sender.velocityInView(self.view)
let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))
let slideMultiplier = magnitude / 200
let slideFactor = 0.1 * slideMultiplier
var finalPoint = CGPoint(x:sender.view!.center.x + (velocity.x * slideFactor), y: sender.view!.center.y + (velocity.y * slideFactor))
finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width)
finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height)
UIView.animateWithDuration(Double(slideFactor * 2), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {sender.view!.center = finalPoint }, completion: nil)
}
}
@IBAction func handlePinch(sender: UIPinchGestureRecognizer) {
sender.view!.transform = CGAffineTransformScale((sender.view!.transform), sender.scale, sender.scale)
sender.scale = 1
}
@IBAction func handleRotate(sender: UIRotationGestureRecognizer) {
sender.view!.transform = CGAffineTransformRotate(sender.view!.transform, sender.rotation)
sender.rotation = 0
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| mit | 6205493d99e29e376f30ca1995a32ced | 35.938462 | 186 | 0.656393 | 4.930185 | false | false | false | false |
Miramas/PurpleLabel | PurpleLabel/Classes/PurpleLabel.swift | 1 | 482 | public class PurpleLabel : UILabel {
public func startBlinking() {
self.backgroundColor = UIColor.purple
self.textColor = UIColor.green
let options : UIViewAnimationOptions = [.repeat, .autoreverse]
UIView.animate(withDuration: 0.25, delay:0.0, options:options, animations: {
self.alpha = 0
}, completion: nil)
}
public func stopBlinking() {
alpha = 1
layer.removeAllAnimations()
}
}
| mit | 5b1403bb4dd1967a3d95ad72202efe3b | 29.125 | 84 | 0.605809 | 4.72549 | false | false | false | false |
carabina/QueryKit | QueryKit/Attribute.swift | 1 | 2355 | //
// Attribute.swift
// QueryKit
//
// Created by Kyle Fuller on 19/06/2014.
//
//
import Foundation
class Attribute<T> : Equatable {
let name:String
init(_ name:String) {
self.name = name
}
/// Builds a compound attribute with other key paths
convenience init(attributes:Array<String>) {
self.init(".".join(attributes))
}
// Sorting
var expression:NSExpression {
return NSExpression(forKeyPath: name)
}
func ascending() -> NSSortDescriptor {
return NSSortDescriptor(key: name, ascending: true)
}
func descending() -> NSSortDescriptor {
return NSSortDescriptor(key: name, ascending: false)
}
}
func == <T>(lhs: Attribute<T>, rhs: Attribute<T>) -> Bool {
return lhs.name == rhs.name
}
@infix func == <T>(left: Attribute<T>, right: T) -> NSPredicate {
return left.expression == NSExpression(forConstantValue: bridgeToObjectiveC(right))
}
@infix func != <T>(left: Attribute<T>, right: T) -> NSPredicate {
return left.expression != NSExpression(forConstantValue: bridgeToObjectiveC(right))
}
@infix func > <T>(left: Attribute<T>, right: T) -> NSPredicate {
return left.expression > NSExpression(forConstantValue: bridgeToObjectiveC(right))
}
@infix func >= <T>(left: Attribute<T>, right: T) -> NSPredicate {
return left.expression >= NSExpression(forConstantValue: bridgeToObjectiveC(right))
}
@infix func < <T>(left: Attribute<T>, right: T) -> NSPredicate {
return left.expression < NSExpression(forConstantValue: bridgeToObjectiveC(right))
}
@infix func <= <T>(left: Attribute<T>, right: T) -> NSPredicate {
return left.expression <= NSExpression(forConstantValue: bridgeToObjectiveC(right))
}
// Bool Attributes
@prefix func ! (left: Attribute<Bool>) -> NSPredicate {
return left == false
}
extension QuerySet {
func filter(attribute:Attribute<Bool>) -> QuerySet<T> {
return filter(attribute == true)
}
func exclude(attribute:Attribute<Bool>) -> QuerySet<T> {
return filter(attribute == false)
}
}
// Collections
func count(attribute:Attribute<NSSet>) -> Attribute<Int> {
return Attribute<Int>(attributes: [attribute.name, "@count"])
}
func count(attribute:Attribute<NSOrderedSet>) -> Attribute<Int> {
return Attribute<Int>(attributes: [attribute.name, "@count"])
}
| bsd-2-clause | 265d3e165078d49d70e4821268a980e2 | 25.166667 | 87 | 0.670913 | 3.978041 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | GoDToolOSX/Views/PopUp Buttons/GoDEnumerablePopUpButton.swift | 1 | 5085 | //
// GoDEnumerablePopUpButton.swift
// GoD Tool
//
// Created by Stars Momodu on 07/10/2019.
//
import Foundation
// Should be class GoDEnumerableButton<T: XGEnumerable>: GoDPopUpButton {
// but doesn't work with interface builder atm because objc doesn't do generics
//class GoDEnumerableButton: GoDPopUpButton {
// private let allValues = [Any]()
//
// func selectedValue<T: XGEnumerable>() -> T {
// return allValues[self.indexOfSelectedItem] as! T
// }
//
// func select<T: XGEnumerable>(_ value: T) {
// self.selectItem(withTitle: value.enumerableName)
// }
//
// override func setUpItems() {
// let values = allValues.map { (item) -> String in
// return item.enumerableName
// }
// self.setTitles(values: values)
// }
//}
protocol GoDEnumerableButton: GoDPopUpButton {
associatedtype Element: XGEnumerable
var allValues: [Element] { get }
var selectedValue: Element { get }
func select(_ value: Element)
func setUpEnumerableItems()
}
extension GoDEnumerableButton where Self: GoDPopUpButton {
private func nameForElement(_ element: Element) -> String {
let value = element.enumerableValue == nil ? "" : " (\(element.enumerableValue!))"
return element.enumerableName + value
}
var selectedValue: Element {
return allValues[self.indexOfSelectedItem]
}
func select(_ value: Element) {
self.selectItem(withTitle: nameForElement(value))
}
func setUpEnumerableItems() {
let values = allValues.map(nameForElement)
self.setTitles(values: values)
}
}
class GoDAbilityPopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGAbilities
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDBattleStylePopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGBattleStyles
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDEffectivenessPopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGEffectivenessValues
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDExpRatePopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGExpRate
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDGenderPopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGGenders
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDGenderRatioPopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGGenderRatios
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDMovePopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGMoves
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDNaturePopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGNatures
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDShinyValuesPopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGShinyValues
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
class GoDTypePopUpButton: GoDPopUpButton, GoDEnumerableButton {
typealias Element = XGMoveTypes
lazy var allValues = Element.allValues
override func setUpItems() {
setUpEnumerableItems()
}
}
//typealias GoDAbilityPopUpButton = GoDEnumerableButton<XGAbilities>
//typealias GoDBattleStylePopUpButton = GoDEnumerableButton<XGBattleStyles>
//typealias GoDBattleTypePopUpButton = GoDEnumerableButton<XGBattleTypes>
//typealias GoDCategoryPopUpButton = GoDEnumerableButton<XGMoveCategories>
//typealias GoDDirectionPopUpButton = GoDEnumerableButton<XGElevatorDirections>
//typealias GoDEffectivenessPopUpButton = GoDEnumerableButton<XGEffectivenessValues>
//typealias GoDEvolutionMethodPopUpButton = GoDEnumerableButton<XGEvolutionMethods>
//typealias GoDExpRatePopUpButton = GoDEnumerableButton<XGExpRate>
//typealias GoDGenderPopUpButton = GoDEnumerableButton<XGGenders>
//typealias GoDGenderRatioPopUpButton = GoDEnumerableButton<XGGenderRatios>
//typealias GoDItemPopUpButton = GoDEnumerableButton<XGItems>
//typealias GoDMovePopUpButton = GoDEnumerableButton<XGMoves>
//typealias GoDMoveEffectTypesPopUpButton = GoDEnumerableButton<XGMoveEffectTypes>
//typealias GoDNaturePopUpButton = GoDEnumerableButton<XGNatures>
//typealias GoDPocketPopUpButton = GoDEnumerableButton<XGBagSlots>
//typealias GoDPokemonPopUpButton = GoDEnumerableButton<XGPokemon>
//typealias GoDTargetsPopUpButton = GoDEnumerableButton<XGMoveTargets>
//typealias GoDTrainerClassPopUpButton = GoDEnumerableButton<XGTrainerClasses>
//typealias GoDTrainerModelPopUpButton = GoDEnumerableButton<XGTrainerModels>
//typealias GoDTypePopUpButton = GoDEnumerableButton<XGMoveTypes>
| gpl-2.0 | a876c2f9e77d019ebe7844086e83da0b | 32.453947 | 84 | 0.779154 | 4.258794 | false | false | false | false |
CNKCQ/oschina | OSCHINA/Extensions/UIImage+Extension.swift | 1 | 2250 | //
// Copyright © 2016年 Jack. All rights reserved.
// Created by KingCQ on 16/8/3.
//
import UIKit
extension UIImage {
/** 缩放 */
public func resize(_ size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
draw(in: CGRect(origin: CGPoint.zero, size: size))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return UIImage()
}
UIGraphicsEndImageContext()
return image
}
/** 切图 */
public func crop(with rect: CGRect) -> UIImage {
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0)
draw(at: CGPoint(x: -rect.origin.x, y: -rect.origin.y))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return UIImage()
}
UIGraphicsEndImageContext()
return image
}
/** 生成纯色图片, 默认大小1x1, 在UITableViewCell默认左侧图标使用时需要手动设定大小占位 */
public class func image(with color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) -> UIImage {
UIGraphicsBeginImageContext(size)
color.set()
UIRectFill(CGRect(origin: CGPoint.zero, size: size))
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return UIImage()
}
UIGraphicsEndImageContext()
return image
}
class func image(with view: UIView) -> UIImage {
UIGraphicsBeginImageContext(view.bounds.size)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return UIImage()
}
UIGraphicsEndImageContext()
return image
}
func imageClipOval() -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let ctx = UIGraphicsGetCurrentContext()
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
ctx?.addEllipse(in: rect)
ctx?.clip()
draw(in: rect)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
return UIImage()
}
UIGraphicsEndImageContext()
return image
}
}
| mit | a00bf23c36bf1aae5cad1aaf94d50981 | 32.015152 | 105 | 0.630106 | 4.974886 | false | false | false | false |
skyPeat/DoYuLiveStreaming | DoYuLiveStreaming/DoYuLiveStreaming/Classes/Home/ViewModel/SP_RecommendViewModel.swift | 1 | 3690 | //
// SP_RecommendViewModel.swift
// DoYuLiveStreaming
//
// Created by tianfeng pan on 17/3/24.
// Copyright © 2017年 tianfeng pan. All rights reserved.
//
import UIKit
/*
#pragma mark- 接口名称:顶部轮播数据
接口地址:http://www.douyutv.com/api/v1/slide/6
请求参数:</br>
参数名称 参数说明
version 当前版本号:2.300
#pragma mark- 接口名称:大数据数据(第一组热门数据)
接口地址:http://capi.douyucdn.cn/api/v1/getbigDataRoom
请求参数:</br>
参数名称 参数说明
time 获取当前时间的字符串
*/
class SP_RecommendViewModel{
lazy var groupModel : [SP_GroupModel] = [SP_GroupModel]()
lazy var bigDataRoomGroup : SP_GroupModel = SP_GroupModel()
lazy var VerticalRoomGroup : SP_GroupModel = SP_GroupModel()
}
//MARK:- 发送网络请求
extension SP_RecommendViewModel{
func requestData(finishedCallBack:@escaping () -> ()){
// 定义参数
let parameters : [String : Any] = ["time":NSDate.currentDate(),"limit":4,"offset":0]
let dispatchGroup = DispatchGroup()
// 0、请求第一组数据
dispatchGroup.enter()
SP_NetWorkingTool.request(type: .get, urlString: SP_MainUrl.appending("bigDataRoom"), parameters: ["time":NSDate.currentDate()]) { (result) in
// 0、获取请求的数据
guard let resultDict = result as? [String : NSObject] else{return}
guard let resultArray = resultDict["data"] as? [[String : NSObject]] else {return}
// 1、字典数组转模型数组
self.bigDataRoomGroup.tag_name = "热门"
self.bigDataRoomGroup.icon_name = "home_header_hot"
for dict in resultArray{
let anchor = SP_AnchorModel(dict: dict)
self.bigDataRoomGroup.anchorModels.append(anchor)
}
dispatchGroup.leave()
}
// 1、请求第二组数据
dispatchGroup.enter()
SP_NetWorkingTool.request(type: .get, urlString: SP_MainUrl.appending("VerticalRoom"), parameters: parameters) { (result) in
// 0、获取请求的数据
guard let resultDict = result as? [String : NSObject] else{return}
guard let resultArray = resultDict["data"] as? [[String : NSObject]] else {return}
// 1、字典数组转模型数组
self.VerticalRoomGroup.tag_name = "颜值"
self.VerticalRoomGroup.icon_name = "lvChaBiao"
for dict in resultArray{
let anchor = SP_AnchorModel(dict: dict)
self.VerticalRoomGroup.anchorModels.append(anchor)
}
dispatchGroup.leave()
}
// 2、请求后面的数据
dispatchGroup.enter()
SP_NetWorkingTool.request(type: .get, urlString: SP_MainUrl.appending("HotCate"), parameters: parameters) { (result) in
// 0、获取请求的数据
guard let resultDict = result as? [String : NSObject] else{return}
guard let resultArray = resultDict["data"] as? [[String : NSObject]] else {return}
// 1、字典数组转模型数组
for dict in resultArray {
let groupModel = SP_GroupModel(dict: dict)
self.groupModel.append(groupModel)
}
dispatchGroup.leave()
}
dispatchGroup.notify(queue: DispatchQueue.main) {
self.groupModel.insert(self.VerticalRoomGroup, at: 0)
self.groupModel.insert(self.bigDataRoomGroup, at: 0)
finishedCallBack()
}
}
}
| mit | f74b04002cdc09d031a6d2fca7384638 | 37.825581 | 150 | 0.595987 | 4.091912 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/WKWebView+WMFWebViewControllerJavascript.swift | 1 | 12873 |
import WebKit
import WMF
fileprivate extension Bool{
func toString() -> String {
return self ? "true" : "false"
}
}
@objc enum WMFArticleFooterMenuItem: Int {
case languages, lastEdited, pageIssues, disambiguation, coordinate, talkPage
// Reminder: These are the strings used by the footerMenu JS transform:
private var menuItemTypeString: String {
switch self {
case .languages: return "languages"
case .lastEdited: return "lastEdited"
case .pageIssues: return "pageIssues"
case .disambiguation: return "disambiguation"
case .coordinate: return "coordinate"
case .talkPage: return "talkPage"
}
}
public var menuItemTypeJSPath: String {
return "window.wmf.footerMenu.MenuItemType.\(menuItemTypeString)"
}
public func shouldAddItem(with article: MWKArticle) -> Bool {
switch self {
case .languages where !article.hasMultipleLanguages:
return false
case .pageIssues:
// Always try to add - footer menu JS will hide this if no page issues found.
return true
case .disambiguation:
// Always try to add - footer menu JS will hide this if no disambiguation titles found.
return true
case .coordinate where !CLLocationCoordinate2DIsValid(article.coordinate):
return false
default:
break
}
return true
}
}
fileprivate protocol JSONEncodable: Encodable {
}
fileprivate extension JSONEncodable {
func toJSON() -> String {
guard
let jsonData = try? JSONEncoder().encode(self),
let jsonString = String(data: jsonData, encoding: .utf8)
else {
assertionFailure("Expected JSON string")
return "{}"
}
return jsonString
}
}
fileprivate struct FooterLocalizedStrings: JSONEncodable {
var readMoreHeading: String = ""
var licenseString: String = ""
var licenseSubstitutionString: String = ""
var viewInBrowserString: String = ""
var menuHeading: String = ""
var menuLanguagesTitle: String = ""
var menuLastEditedTitle: String = ""
var menuLastEditedSubtitle: String = ""
var menuTalkPageTitle: String = ""
var menuPageIssuesTitle: String = ""
var menuDisambiguationTitle: String = ""
var menuCoordinateTitle: String = ""
init(for article: MWKArticle) {
let lang = (article.url as NSURL).wmf_language
readMoreHeading = WMFLocalizedString("article-read-more-title", language: lang, value: "Read more", comment: "The text that is displayed before the read more section at the bottom of an article\n{{Identical|Read more}}").uppercased(with: Locale.current)
licenseString = String.localizedStringWithFormat(WMFLocalizedString("license-footer-text", language: lang, value: "Content is available under %1$@ unless otherwise noted.", comment: "Marker at page end for who last modified the page when anonymous. %1$@ is a relative date such as '2 months ago' or 'today'."), "$1")
licenseSubstitutionString = WMFLocalizedString("license-footer-name", language: lang, value: "CC BY-SA 3.0", comment: "License short name; usually leave untranslated as CC-BY-SA 3.0\n{{Identical|CC BY-SA}}")
viewInBrowserString = WMFLocalizedString("view-in-browser-footer-link", language: lang, value: "View article in browser", comment: "Link to view article in browser")
menuHeading = WMFLocalizedString("article-about-title", language: lang, value: "About this article", comment: "The text that is displayed before the 'about' section at the bottom of an article").uppercased(with: Locale.current)
menuLanguagesTitle = String.localizedStringWithFormat(WMFLocalizedString("page-read-in-other-languages", language: lang, value: "Available in {{PLURAL:%1$d|%1$d other language|%1$d other languages}}", comment: "Label for button showing number of languages an article is available in. %1$@ will be replaced with the number of languages"), article.languagecount)
let lastModified = article.lastmodified ?? Date()
let days = NSCalendar.wmf_gregorian().wmf_days(from: lastModified, to: Date())
menuLastEditedTitle = String.localizedStringWithFormat(WMFLocalizedString("page-last-edited", language: lang, value: "{{PLURAL:%1$d|0=Edited today|1=Edited yesterday|Edited %1$d days ago}}", comment: "Relative days since an article was last edited. 0 = today, singular = yesterday. %1$d will be replaced with the number of days ago."), days)
menuLastEditedSubtitle = WMFLocalizedString("page-edit-history", language: lang, value: "Full edit history", comment: "Label for button used to show an article's complete edit history")
menuTalkPageTitle = WMFLocalizedString("page-talk-page", language: lang, value: "View talk page", comment: "Label for button linking out to an article's talk page")
menuPageIssuesTitle = WMFLocalizedString("page-issues", language: lang, value: "Page issues", comment: "Label for the button that shows the \"Page issues\" dialog, where information about the imperfections of the current page is provided (by displaying the warning/cleanup templates).\n{{Identical|Page issue}}")
menuDisambiguationTitle = WMFLocalizedString("page-similar-titles", language: lang, value: "Similar pages", comment: "Label for button that shows a list of similar titles (disambiguation) for the current page")
menuCoordinateTitle = WMFLocalizedString("page-location", language: lang, value: "View on a map", comment: "Label for button used to show an article on the map")
}
}
fileprivate struct CollapseTablesLocalizedStrings: JSONEncodable {
var tableInfoboxTitle: String = ""
var tableOtherTitle: String = ""
var tableFooterTitle: String = ""
init(for lang: String?) {
tableInfoboxTitle = WMFLocalizedString("info-box-title", language: lang, value: "Quick Facts", comment: "The title of infoboxes – in collapsed and expanded form")
tableOtherTitle = WMFLocalizedString("table-title-other", language: lang, value: "More information", comment: "The title of non-info box tables - in collapsed and expanded form\n{{Identical|More information}}")
tableFooterTitle = WMFLocalizedString("info-box-close-text", language: lang, value: "Close", comment: "The text for telling users they can tap the bottom of the info box to close it\n{{Identical|Close}}")
}
}
extension WKWebView {
@objc static public func wmf_themeApplicationJavascript(with theme: Theme?) -> String {
var jsThemeConstant = "DEFAULT"
guard let theme = theme else {
return jsThemeConstant
}
var isDim = false
switch theme.name {
case Theme.sepia.name:
jsThemeConstant = "SEPIA"
case Theme.blackDimmed.name:
isDim = true
fallthrough
case Theme.black.name:
jsThemeConstant = "BLACK"
case Theme.darkDimmed.name:
isDim = true
fallthrough
case Theme.dark.name:
jsThemeConstant = "DARK"
default:
break
}
return """
window.wmf.themes.setTheme(document, window.wmf.themes.THEME.\(jsThemeConstant))
window.wmf.imageDimming.dim(window, \(isDim.toString()))
"""
}
@objc public func wmf_applyTheme(_ theme: Theme){
let themeJS = WKWebView.wmf_themeApplicationJavascript(with: theme)
evaluateJavaScript(themeJS, completionHandler: nil)
}
private func languageJS(for article: MWKArticle) -> String {
let lang = (article.url as NSURL).wmf_language ?? MWKLanguageLinkController.sharedInstance().appLanguage?.languageCode ?? "en"
let langInfo = MWLanguageInfo(forCode: lang)
let langCode = langInfo.code
let langDir = langInfo.dir
return """
new window.wmf.sections.Language(
'\(langCode.wmf_stringBySanitizingForJavaScript())',
'\(langDir.wmf_stringBySanitizingForJavaScript())',
\((langDir == "rtl").toString())
)
"""
}
private func articleJS(for article: MWKArticle, title: String) -> String {
let articleDisplayTitle = article.displaytitle ?? ""
let articleEntityDescription = (article.entityDescription ?? "").wmf_stringByCapitalizingFirstCharacter(usingWikipediaLanguage: article.url.wmf_language)
let addTitleDescriptionLocalizedString = WMFLocalizedString("description-add-link-title", language: (article.url as NSURL).wmf_language, value: "Add title description", comment: "Text for link for adding a title description")
return """
new window.wmf.sections.Article(
\(article.isMain.toString()),
'\(title.wmf_stringBySanitizingForJavaScript())',
'\(articleDisplayTitle.wmf_stringBySanitizingForJavaScript())',
'\(articleEntityDescription.wmf_stringBySanitizingForJavaScript())',
\(article.editable.toString()),
\(languageJS(for: article)),
'\(addTitleDescriptionLocalizedString.wmf_stringBySanitizingForJavaScript())',
\(article.isWikidataDescriptionEditable.toString())
)
"""
}
private func menuItemsJS(for article: MWKArticle) -> String {
let menuItemTypeJSPaths = [
WMFArticleFooterMenuItem.languages,
WMFArticleFooterMenuItem.coordinate,
WMFArticleFooterMenuItem.lastEdited,
WMFArticleFooterMenuItem.pageIssues,
WMFArticleFooterMenuItem.disambiguation,
WMFArticleFooterMenuItem.talkPage
]
.filter{$0.shouldAddItem(with: article)}
.map{$0.menuItemTypeJSPath}
return "[\(menuItemTypeJSPaths.joined(separator: ", "))]"
}
@objc public func wmf_fetchTransformAndAppendSectionsToDocument(_ article: MWKArticle, collapseTables: Bool, scrolledTo fragment: String?){
guard
let url = article.url,
let host = url.host,
let appSchemeURL = SchemeHandler.APIHandler.appSchemeURL(for: host, fragment: nil),
let apiURL = SchemeHandler.ArticleSectionHandler.appSchemeURL(for: url, targetImageWidth: self.traitCollection.wmf_articleImageWidth)
else {
assertionFailure("Expected url, appSchemeURL and encodedTitle")
return
}
// https://github.com/wikimedia/wikipedia-ios/pull/1334/commits/f2b2228e2c0fd852479464ec84e38183d1cf2922
let appSchemeURLString = appSchemeURL.absoluteString
let apiURLString = apiURL.absoluteString
let title = (article.url as NSURL).wmf_title ?? ""
let articleContentLoadedCallbackJS = """
() => {
const footer = new window.wmf.footers.Footer(
'\(title.wmf_stringBySanitizingForJavaScript())',
\(menuItemsJS(for: article)),
\(article.hasReadMore.toString()),
3,
\(FooterLocalizedStrings.init(for: article).toJSON()),
'\(appSchemeURLString.wmf_stringBySanitizingForJavaScript())'
)
footer.add()
window.requestAnimationFrame(() => {
window.webkit.messageHandlers.articleState.postMessage('articleContentLoaded')
})
}
"""
let sectionErrorMessageLocalizedString = WMFLocalizedString("article-unable-to-load-section", language: (article.url as NSURL).wmf_language, value: "Unable to load this section. Try refreshing the article to see if it fixes the problem.", comment: "Displayed within the article content when a section fails to render for some reason.")
evaluateJavaScript("""
window.wmf.sections.sectionErrorMessageLocalizedString = '\(sectionErrorMessageLocalizedString.wmf_stringBySanitizingForJavaScript())'
window.wmf.sections.collapseTablesLocalizedStrings = \(CollapseTablesLocalizedStrings.init(for: (article.url as NSURL).wmf_language).toJSON())
window.wmf.sections.collapseTablesInitially = \(collapseTables ? "true" : "false")
window.wmf.sections.fetchTransformAndAppendSectionsToDocument(
\(articleJS(for: article, title: title)),
'\(apiURLString.wmf_stringBySanitizingForJavaScript())',
'\((fragment ?? "").wmf_stringBySanitizingForJavaScript())',
\(articleContentLoadedCallbackJS)
)
""") { (result, error) in
guard let error = error else {
return
}
DDLogError("Error when evaluating javascript on fetch and transform: \(error)")
}
}
}
| mit | 3da295390b89e913a8b40e763ffa7584 | 51.534694 | 368 | 0.665916 | 4.702594 | false | false | false | false |
johnno1962d/swift | test/attr/attr_objc.swift | 1 | 83288 | // RUN: %target-parse-verify-swift
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module | FileCheck %s
// RUN: not %target-swift-frontend -parse -dump-ast -disable-objc-attr-requires-foundation-module %s 2> %t.dump
// RUN: FileCheck -check-prefix CHECK-DUMP %s < %t.dump
// REQUIRES: objc_interop
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
@objc class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc protocol Protocol_ObjC1 {}
@objc protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc extension PlainClass { } // expected-error{{@objc cannot be applied to this declaration}}{{1-7=}}
@objc
var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_getterSetter: Int {
@objc
get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
return 0
}
@objc
set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
@objc
didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var instanceVar3: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
}
}
class subject_staticVar1 {
@objc
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc
class var staticVar2: Int { return 42 }
}
@objc
func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
@objc
func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc
class subject_class1 { // no-error
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no-error
}
@objc
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc
var subject_instanceVar: Int // no-error
@objc
init(foo: Int) {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc var extProp: Int { return 0 } // expected-error{{@objc is not supported within extensions of generic classes}}
@objc func extFoo() {} // expected-error{{@objc is not supported within extensions of generic classes}}
}
@objc
enum subject_enum: Int {
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2)
case subject_enumElement2
@objc(subject_enumElement3)
case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-8=}}
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
@nonobjc // expected-error {{@nonobjc cannot be applied to this declaration}}
case subject_enumElement7
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
enum subject_enum2 {
@objc(subject_enum2Element1)
case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-8=}}
}
@objc
protocol subject_protocol1 {
@objc
var subject_instanceVar: Int { get }
@objc
func subject_instanceFunc()
}
@objc protocol subject_protocol2 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc protocol subject_protocol3 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc
var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
@objc
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc
protocol subject_containerObjCProtocol2 {
init(a: Int)
@objc init(a: Double)
func func1() -> Int
@objc func func1_() -> Int
var instanceVar1: Int { get set }
@objc var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc func dynamicSelf1_() -> Self { return self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func genericParams<T: NSObject>() -> [T] { return [] }
// expected-error@-1{{method cannot be marked @objc because it has generic parameters}}
}
func genericContext1<T>(_: T) {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' nested in generic function 'genericContext1' is not allowed}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' nested in generic function 'genericContext1' is not allowed}}
class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' nested in generic function 'genericContext1' is not allowed}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' nested in generic function 'genericContext1' is not allowed}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' nested in generic function 'genericContext1' is not allowed}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{nested in generic type}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{nested in generic type}}
@objc
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested { // expected-error{{nested in generic type}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {} // expected-error{{nested in generic type}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{nested in generic type}}
@objc
func f() {} // no-error
}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}}
}
class subject_subscriptIndexed1 {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc
subscript(a: protocol<Protocol_ObjC1, Protocol_ObjC2>) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc
subscript(a: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid2 {
@objc
subscript(a: PlainClass) -> Int {
// expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc
subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc
subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc
subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc
subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'PlainProtocol' is not '@objc'}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc
subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc
subscript(a: protocol<Protocol_Class1, Protocol_Class2>) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}}
get { return 0 }
}
}
//===--- Tests for @objc inference.
@objc
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc func func7_(a: PlainClass) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc func func7m_(a: PlainClass.Type) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc func func8_() -> PlainClass {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc func func8m_() -> PlainClass.Type {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc func func9_(a: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc func func10_() -> PlainStruct {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc func func11_(a: PlainEnum) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc func func12_(a: PlainProtocol) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc func func14_(a: Protocol_Class1) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc func func16_(a: AnyObject) {} // no-error
func func17(a: () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: () -> ()) {
@objc func func17_(a: () -> ()) {}
func func18(a: (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: (Int) -> (), b: Int)
@objc func func18_(a: (Int) -> (), b: Int) {}
func func19(a: (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: (String) -> (), b: Int) {
@objc func func19_(a: (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> protocol<> {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
// expected-error@-5 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-6 {{'protocol<>' is not considered '@objc'; use 'AnyObject' instead}}
@objc func func_UnnamedParam1(_: Int) {} // no-error
@objc func func_UnnamedParam2(_: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var intstanceVar4: Int {
// CHECK: @objc var intstanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var intstanceVar5: Int {
// CHECK: @objc var intstanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @objc var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} final willSet {}
didSet {}
// CHECK-NEXT: {{^}} final didSet {}
}
@objc var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} final willSet {}
didSet {}
// CHECK-NEXT: {{^}} final didSet {}
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: UnicodeScalar
// CHECK-LABEL: @objc var var_Char: UnicodeScalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} var var_tuple1: ()
@objc var var_tuple1_: ()
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} var var_tuple2: Void
@objc var var_tuple2_: Void
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc var var_tuple4_: (Int, Int)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc var var_PlainClass_: PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc var var_PlainStruct_: PlainStruct
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc var var_PlainEnum_: PlainEnum
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc var var_PlainProtocol_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc var var_ProtocolClass_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc var var_PlainClassMetatype_: PlainClass.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc var var_PlainStructMetatype_: PlainStruct.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc var var_PlainEnumMetatype_: PlainEnum.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc var var_PlainExistentialMetatype_: PlainProtocol.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc var var_ProtocolClassMetatype_: Protocol_Class1.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: protocol<>
// CHECK-LABEL: {{^}} var var_Existential0: protocol<>
@objc var var_Existential0_: protocol<>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{'protocol<>' is not considered '@objc'; use 'AnyObject' instead}}
var var_Existential1: protocol<PlainProtocol>
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc var var_Existential1_: protocol<PlainProtocol>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential2: protocol<PlainProtocol, PlainProtocol>
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc var var_Existential2_: protocol<PlainProtocol, PlainProtocol>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential3: protocol<PlainProtocol, Protocol_Class1>
// CHECK-LABEL: {{^}} var var_Existential3: protocol<PlainProtocol, Protocol_Class1>
@objc var var_Existential3_: protocol<PlainProtocol, Protocol_Class1>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential4: protocol<PlainProtocol, Protocol_ObjC1>
// CHECK-LABEL: {{^}} var var_Existential4: protocol<PlainProtocol, Protocol_ObjC1>
@objc var var_Existential4_: protocol<PlainProtocol, Protocol_ObjC1>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential5: protocol<Protocol_Class1>
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc var var_Existential5_: protocol<Protocol_Class1>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential6: protocol<Protocol_Class1, Protocol_Class2>
// CHECK-LABEL: {{^}} var var_Existential6: protocol<Protocol_Class1, Protocol_Class2>
@objc var var_Existential6_: protocol<Protocol_Class1, Protocol_Class2>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential7: protocol<Protocol_Class1, Protocol_ObjC1>
// CHECK-LABEL: {{^}} var var_Existential7: protocol<Protocol_Class1, Protocol_ObjC1>
@objc var var_Existential7_: protocol<Protocol_Class1, Protocol_ObjC1>
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential8: protocol<Protocol_ObjC1>
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc var var_Existential8_: protocol<Protocol_ObjC1> // no-error
var var_Existential9: protocol<Protocol_ObjC1, Protocol_ObjC2>
// CHECK-LABEL: @objc var var_Existential9: protocol<Protocol_ObjC1, Protocol_ObjC2>
@objc var var_Existential9_: protocol<Protocol_ObjC1, Protocol_ObjC2> // no-error
var var_ExistentialMetatype0: protocol<>.Type
var var_ExistentialMetatype1: protocol<PlainProtocol>.Type
var var_ExistentialMetatype2: protocol<PlainProtocol, PlainProtocol>.Type
var var_ExistentialMetatype3: protocol<PlainProtocol, Protocol_Class1>.Type
var var_ExistentialMetatype4: protocol<PlainProtocol, Protocol_ObjC1>.Type
var var_ExistentialMetatype5: protocol<Protocol_Class1>.Type
var var_ExistentialMetatype6: protocol<Protocol_Class1, Protocol_Class2>.Type
var var_ExistentialMetatype7: protocol<Protocol_Class1, Protocol_ObjC1>.Type
var var_ExistentialMetatype8: protocol<Protocol_ObjC1>.Type
var var_ExistentialMetatype9: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: protocol<>.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: protocol<PlainProtocol, Protocol_Class1>.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: protocol<PlainProtocol, Protocol_ObjC1>.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: protocol<Protocol_Class1, Protocol_Class2>.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: protocol<Protocol_Class1, Protocol_ObjC1>.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutablePointer<()>
var var_UnsafeMutablePointer101: UnsafeMutablePointer<Void>
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutablePointer<()>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutablePointer<Void>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: protocol<Protocol_ObjC1>?
var var_Optional9: protocol<Protocol_ObjC1>.Type?
var var_Optional10: protocol<Protocol_ObjC1, Protocol_ObjC2>?
var var_Optional11: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional5: AnyObject?
// CHECK-LABEL: @objc var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc var var_Optional7: String?
// CHECK-LABEL: @objc var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional10: protocol<Protocol_ObjC1, Protocol_ObjC2>?
// CHECK-LABEL: @objc var var_Optional11: protocol<Protocol_ObjC1, Protocol_ObjC2>.Type?
// CHECK-LABEL: @objc var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: protocol<Protocol_ObjC1>!
var var_ImplicitlyUnwrappedOptional9: protocol<Protocol_ObjC1, Protocol_ObjC2>!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional9: protocol<Protocol_ObjC1, Protocol_ObjC2>!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail9: protocol<>?
var var_Optional_fail10: protocol<PlainProtocol>?
var var_Optional_fail11: protocol<PlainProtocol, Protocol_ObjC1>?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) PlainStruct -> Int
var var_CFunctionPointer_invalid_2: @convention(c) PlainStruct -> Int // expected-error {{'PlainStruct -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: protocol<Protocol_ObjC1>?
weak var var_Weak8: protocol<Protocol_ObjC1, Protocol_ObjC2>?
// CHECK-LABEL: @objc weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc weak var var_Weak8: @sil_weak protocol<Protocol_ObjC1, Protocol_ObjC2>
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: protocol<Protocol_ObjC1>
unowned var var_Unowned8: protocol<Protocol_ObjC1, Protocol_ObjC2>
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned protocol<Protocol_ObjC1, Protocol_ObjC2>
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) AnyObject -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) AnyObject -> AnyObject]
@objc var var_ArrayType2_: [@convention(block) AnyObject -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc var var_ArrayType3_: [PlainStruct]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [AnyObject -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [AnyObject -> AnyObject]
@objc var var_ArrayType4_: [AnyObject -> AnyObject]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc var var_ArrayType7_: [PlainClass]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc var var_ArrayType8_: [PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [protocol<Protocol_ObjC1, PlainProtocol>]
// CHECK-LABEL: {{^}} var var_ArrayType9: [protocol<{{.+}}>]
@objc var var_ArrayType9_: [protocol<Protocol_ObjC1, PlainProtocol>]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [protocol<Protocol_ObjC1, Protocol_ObjC2>]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [protocol<{{.+}}>]
@objc var var_ArrayType10_: [protocol<Protocol_ObjC1, Protocol_ObjC2>]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: {{^}} var var_ArrayType11: [Any]
@objc var var_ArrayType11_: [Any]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType12: [Any!]
// CHECK-LABEL: {{^}} var var_ArrayType12: [Any!]
@objc var var_ArrayType12_: [Any!]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc var var_ArrayType13_: [Any?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType14: [AnyObject!]
// CHECK-LABEL: {{^}} var var_ArrayType14: [AnyObject!]
@objc var var_ArrayType14_: [AnyObject!]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc var var_ArrayType15_: [AnyObject?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) AnyObject -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) AnyObject -> AnyObject]]
@objc var var_ArrayType16_: [[@convention(block) AnyObject -> AnyObject]] // no-error
var var_ArrayType17: [[AnyObject -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[AnyObject -> AnyObject]]
@objc var var_ArrayType17_: [[AnyObject -> AnyObject]]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc var var_GP_Unconstrained_: GP_Unconstrained
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc var var_GP_PlainClass_: GP_PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc var var_GP_PlainProtocol_: GP_PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc var var_GP_Class_ObjC_: GP_Class_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc var var_GP_Protocol_Class_: GP_Protocol_Class
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc var v1: Int
}
@objc
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc
var intstanceVar1: Int {
// CHECK: @objc var intstanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @IBOutlet @objc weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @NSManaged @objc dynamic var goodManaged: Class_ObjC1
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @NSManaged var badManaged: PlainStruct
}
//===---
//===--- Pointer argument types
//===---
@objc class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2)
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice)
init(foo: ()) { }
@objc(initWithIntent)
init(bar _: ()) { }
@objc(initForMurder)
init() { }
@objc(isFoo)
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error{{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:)
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:)
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::)
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc
enum BadEnum2: Int {
@objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc var prop: Int {
@objc(property) get { return _prop }
@objc(setProperty:) set { _prop = newValue }
}
var prop2: Int {
@objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}}
@objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}}
}
var prop3: Int {
@objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) get {
return c
}
@objc(setAtClass:class:) set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo)
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo)
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc class ClosureArguments {
// CHECK: @objc func foo
@objc func foo(f: Int -> ()) {}
// CHECK: @objc func bar
@objc func bar(f: NotObjCEnum -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc func bas(f: NotObjCEnum -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: Int -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: NotObjCEnum -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: NotObjCEnum -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) Int -> ()
typealias BadBlock = @convention(block) NotObjCEnum -> () // expected-error{{'NotObjCEnum -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
}
@objc class Load2 {
class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
}
@objc class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
@objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
final var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc init(degrees: Double) throws { }
// Errors
@objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
}
// CHECK-DUMP-LABEL: class_decl "ImplicitClassThrows1"
@objc class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl "methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=Bool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl "methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int, fn3: (Int) -> Int)
// CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=Bool
func methodWithTrailingClosures(_ s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int, fn3: (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl "init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
}
// CHECK-DUMP-LABEL: class_decl "SubclassImplicitClassThrows1"
@objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: ((Int) -> Int), fn2: ((Int) -> Int), fn3: ((Int) -> Int))
// CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=Bool
override func methodWithTrailingClosures(_ s: String, fn1: ((Int) -> Int), fn2: ((Int) -> Int), fn3: ((Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}}
@objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}}
@objc func method3(_ x: Int, error: Int, closure: Int -> Int) { } // expected-note{{declared here}}
@objc func method3(_ x: Int, closure: Int -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}}
@objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}}
@objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}}
@objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: Int -> Int) { } // expected-note{{declared here}}
@objc init(fn: Int -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) func method4(x: Int, closure: Int -> Int) throws { }
@objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: Int -> Int) throws { }
@objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
@objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
// CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=Bool
@objc(method8:fn1:error:fn2:)
func method8(_ s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { }
// CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=Bool
@objc(method9AndReturnError:s:fn1:fn2:)
func method9(_ s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=Bool
override func method8(_ s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { }
// CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=Bool
override func method9(_ s: String, fn1: ((Int) -> Int), fn2: (Int) -> Int) throws { }
}
@objc protocol ProtocolThrowsObjCName {
optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }}
}
@objc class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc class ObjC_Class1 : Hashable {
var hashValue: Int { return 0 }
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
| apache-2.0 | 0fa65ae5502645c2730d48ecfc341253 | 39.509728 | 293 | 0.700713 | 3.827398 | false | false | false | false |
gorjuspixels/DKImagePickerController | DKImagePickerController/View/DKAssetGroupDetailVC.swift | 1 | 20825 | //
// DKAssetGroupDetailVC.swift
// DKImagePickerController
//
// Created by ZhangAo on 15/8/10.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
import AVFoundation
import Photos
private extension UICollectionView {
func indexPathsForElements(in rect: CGRect, _ hidesCamera: Bool) -> [IndexPath] {
let allLayoutAttributes = collectionViewLayout.layoutAttributesForElements(in: rect)!
if hidesCamera {
return allLayoutAttributes.map { $0.indexPath }
} else {
return allLayoutAttributes.flatMap { $0.indexPath.item == 0 ? nil : IndexPath(item: $0.indexPath.item - 1, section: $0.indexPath.section) }
}
}
}
// Show all images in the asset group
public class DKAssetGroupDetailVC: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, DKGroupDataManagerObserver, UIGestureRecognizerDelegate {
private lazy var selectGroupButton: UIButton = {
let button = UIButton()
let globalTitleColor = UINavigationBar.appearance().titleTextAttributes?[NSForegroundColorAttributeName] as? UIColor
button.setTitleColor(globalTitleColor ?? UIColor.black, for: .normal)
let globalTitleFont = UINavigationBar.appearance().titleTextAttributes?[NSFontAttributeName] as? UIFont
button.titleLabel!.font = globalTitleFont ?? UIFont.boldSystemFont(ofSize: 18.0)
button.addTarget(self, action: #selector(DKAssetGroupDetailVC.showGroupSelector), for: .touchUpInside)
return button
}()
public var collectionView: UICollectionView!
internal weak var imagePickerController: DKImagePickerController!
internal var topContainerView: UIView?
private var selectedGroupId: String?
private var groupListVC: DKAssetGroupListVC!
private var hidesCamera: Bool = false
private var footerView: UIView?
private var currentViewSize: CGSize!
private var registeredCellIdentifiers = Set<String>()
private var thumbnailSize = CGSize.zero
public var lastSelectedItemIndex: IndexPath?
public var selectedIndexPaths = [[String:Any]]()
override public func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if let currentViewSize = self.currentViewSize, currentViewSize.equalTo(self.view.bounds.size) {
return
} else {
currentViewSize = self.view.bounds.size
}
self.collectionView?.collectionViewLayout.invalidateLayout()
}
override public func viewDidLoad() {
super.viewDidLoad()
self.addTopContainerView()
let layout = self.imagePickerController.UIDelegate.layoutForImagePickerController(self.imagePickerController).init()
self.collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
self.collectionView.backgroundColor = self.imagePickerController.UIDelegate.imagePickerControllerCollectionViewBackgroundColor()
self.collectionView.allowsMultipleSelection = true
self.collectionView.delegate = self
self.collectionView.dataSource = self
self.view.addSubview(self.collectionView)
//Long Press
let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
longPressGesture.minimumPressDuration = 0.5
longPressGesture.delegate = self
self.collectionView.addGestureRecognizer(longPressGesture)
self.footerView = self.imagePickerController.UIDelegate.imagePickerControllerFooterView(self.imagePickerController)
if let footerView = self.footerView {
self.view.addSubview(footerView)
}
self.hidesCamera = self.imagePickerController.sourceType == .photo
self.checkPhotoPermission()
}
func handleLongPress(longPressGesture:UILongPressGestureRecognizer) {
// ignore if the gesture has not been finished
if (longPressGesture.state != .began) {
return
}
let p = longPressGesture.location(in: self.collectionView)
guard let indexPath = self.collectionView.indexPathForItem(at: p) else { return }
self.imagePickerController.UIDelegate.imagePickerController(self.imagePickerController, didLongPressAt: indexPath)
}
func addTopContainerView() {
if let topContainerView = self.topContainerView {
let width = UIScreen.main.bounds.width
topContainerView.frame = CGRect(x: 0, y: 0, width: width, height: width);
self.view.insertSubview(topContainerView, at: 0)
}
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.updateCachedAssets()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var offsetHeight = CGFloat(0)
if let topContainerView = self.topContainerView {
offsetHeight = topContainerView.frame.height
}
if let footerView = self.footerView {
footerView.frame = CGRect(x: 0, y: self.view.bounds.height - footerView.bounds.height, width: self.view.bounds.width, height: footerView.bounds.height)
self.collectionView.frame = CGRect(x: 0, y: offsetHeight, width: self.view.bounds.width, height: self.view.bounds.height - footerView.bounds.height - offsetHeight)
} else {
self.collectionView.frame = CGRect(x: 0, y: offsetHeight, width: self.view.bounds.width, height: self.view.bounds.height - offsetHeight)
}
}
internal func checkPhotoPermission() {
func photoDenied() {
self.view.addSubview(DKPermissionView.permissionView(.photo))
self.view.backgroundColor = UIColor.black
self.collectionView?.isHidden = true
}
func setup() {
self.resetCachedAssets()
getImageManager().groupDataManager.addObserver(self)
self.groupListVC = DKAssetGroupListVC(selectedGroupDidChangeBlock: { [unowned self] groupId in
self.selectAssetGroup(groupId)
}, defaultAssetGroup: self.imagePickerController.defaultAssetGroup)
self.groupListVC.loadGroups()
}
DKImageManager.checkPhotoPermission { granted in
granted ? setup() : photoDenied()
}
}
func selectAssetGroup(_ groupId: String?) {
if self.selectedGroupId == groupId {
self.updateTitleView()
return
}
self.selectedGroupId = groupId
self.updateTitleView()
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!)
if (group.totalCount > 0) {
let firstAssetCellIndex = self.hidesCamera ? 0 : 1
if let asset = self.fetchAsset(for: firstAssetCellIndex) {
lastSelectedItemIndex = IndexPath(row: firstAssetCellIndex, section: 0)
self.imagePickerController.defaultSelectedAssets = [asset]
if let highlightCallback = self.imagePickerController.didHighlightImage {
// highlight the first cell by default
highlightCallback([asset])
}
}
}
self.collectionView!.reloadData()
}
func updateTitleView() {
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!)
self.title = group.groupName
let groupsCount = getImageManager().groupDataManager.groupIds?.count ?? 0
self.selectGroupButton.setTitle(group.groupName + (groupsCount > 1 ? " \u{25be}" : "" ), for: .normal)
self.selectGroupButton.sizeToFit()
self.selectGroupButton.isEnabled = groupsCount > 1
self.navigationItem.titleView = self.selectGroupButton
}
func showGroupSelector() {
DKPopoverViewController.popoverViewController(self.groupListVC, fromView: self.selectGroupButton)
}
public func fetchAsset(for index: Int) -> DKAsset? {
if !self.hidesCamera && index == 0 {
return nil
}
let assetIndex = (index - (self.hidesCamera ? 0 : 1))
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!)
return getImageManager().groupDataManager.fetchAsset(group, index: assetIndex)
}
func isCameraCell(indexPath: IndexPath) -> Bool {
return indexPath.row == 0 && !self.hidesCamera
}
// MARK: - Cells
func registerCellIfNeeded(cellClass: DKAssetGroupDetailBaseCell.Type) {
let cellReuseIdentifier = cellClass.cellReuseIdentifier()
if !self.registeredCellIdentifiers.contains(cellReuseIdentifier) {
self.collectionView.register(cellClass, forCellWithReuseIdentifier: cellReuseIdentifier)
self.registeredCellIdentifiers.insert(cellReuseIdentifier)
}
}
func dequeueReusableCell(for indexPath: IndexPath) -> DKAssetGroupDetailBaseCell {
let asset = self.fetchAsset(for: indexPath.row)!
let cellClass: DKAssetGroupDetailBaseCell.Type!
if asset.isVideo {
cellClass = self.imagePickerController.UIDelegate.imagePickerControllerCollectionVideoCell()
} else {
cellClass = self.imagePickerController.UIDelegate.imagePickerControllerCollectionImageCell()
}
self.registerCellIfNeeded(cellClass: cellClass)
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: cellClass.cellReuseIdentifier(), for: indexPath) as! DKAssetGroupDetailBaseCell
self.setup(assetCell: cell, for: indexPath, with: asset)
return cell
}
func dequeueReusableCameraCell(for indexPath: IndexPath) -> DKAssetGroupDetailBaseCell {
let cellClass = self.imagePickerController.UIDelegate.imagePickerControllerCollectionCameraCell()
self.registerCellIfNeeded(cellClass: cellClass)
let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: cellClass.cellReuseIdentifier(), for: indexPath)
return cell as! DKAssetGroupDetailBaseCell
}
func setup(assetCell cell: DKAssetGroupDetailBaseCell, for indexPath: IndexPath, with asset: DKAsset) {
cell.asset = asset
cell.isCellFocused = lastSelectedItemIndex == indexPath
let tag = indexPath.row + 1
cell.tag = tag
if self.thumbnailSize.equalTo(CGSize.zero) {
self.thumbnailSize = self.collectionView!.collectionViewLayout.layoutAttributesForItem(at: indexPath)!.size.toPixel()
}
asset.fetchImageWithSize(self.thumbnailSize, options: nil, contentMode: .aspectFill) { (image, info) in
if cell.tag == tag {
cell.thumbnailImage = image
}
}
if let index = self.imagePickerController.selectedAssets.index(of: asset) {
cell.isSelected = true
cell.index = index
self.collectionView!.selectItem(at: indexPath, animated: false, scrollPosition: [])
} else {
cell.isSelected = false
self.collectionView!.deselectItem(at: indexPath, animated: false)
}
}
// MARK: - UICollectionViewDelegate, UICollectionViewDataSource methods
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let selectedGroupId = self.selectedGroupId else { return 0 }
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(selectedGroupId)
return (group.totalCount ?? 0) + (self.hidesCamera ? 0 : 1)
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: DKAssetGroupDetailBaseCell!
if self.isCameraCell(indexPath: indexPath) {
cell = self.dequeueReusableCameraCell(for: indexPath)
} else {
cell = self.dequeueReusableCell(for: indexPath)
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if let firstSelectedAsset = self.imagePickerController.selectedAssets.first,
let selectedAsset = (collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell)?.asset, self.imagePickerController.allowMultipleTypes == false && firstSelectedAsset.isVideo != selectedAsset.isVideo && !self.imagePickerController.singleSelect {
let alert = UIAlertController(
title: DKImageLocalizedStringWithKey("selectPhotosOrVideos")
, message: DKImageLocalizedStringWithKey("selectPhotosOrVideosError")
, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: DKImageLocalizedStringWithKey("ok"), style: .cancel) { _ in })
self.imagePickerController.present(alert, animated: true){}
return false
}
let shouldSelect = self.imagePickerController.selectedAssets.count < self.imagePickerController.maxSelectableCount
if !shouldSelect {
self.imagePickerController.UIDelegate.imagePickerControllerDidReachMaxLimit(self.imagePickerController)
}
return shouldSelect
}
public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
let shouldDeselect = lastSelectedItemIndex == indexPath && !self.imagePickerController.singleSelect
if (!shouldDeselect) {
lastSelectedItemIndex = indexPath
if let cell = collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell, let asset = cell.asset, let highlightCallback = self.imagePickerController.didHighlightImage {
highlightCallback([asset])
}
(collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell)?.isCellFocused = true
collectionView.reloadData()
}
return shouldDeselect
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if self.isCameraCell(indexPath: indexPath) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
self.imagePickerController.presentCamera()
}
} else if let cell = collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell, let selectedAsset = cell.asset {
lastSelectedItemIndex = indexPath
self.imagePickerController.selectImage(selectedAsset)
if let highlightCallback = self.imagePickerController.didHighlightImage {
highlightCallback([selectedAsset])
}
if let cell = collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell {
cell.index = self.imagePickerController.selectedAssets.count - 1
cell.isCellFocused = true
selectedIndexPaths.append(["index": cell.index, "indexPath": indexPath])
}
collectionView.reloadData()
}
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if let cell = (collectionView.cellForItem(at: indexPath) as? DKAssetGroupDetailBaseCell), let removedAsset = cell.asset {
let removedIndex = self.imagePickerController.selectedAssets.index(of: removedAsset)!
if (selectedIndexPaths.count > removedIndex) {
selectedIndexPaths.remove(at: removedIndex)
}
let firstAssetCellIndex = self.hidesCamera ? 0 : 1
lastSelectedItemIndex = selectedIndexPaths.last?["indexPath"] as? IndexPath ?? IndexPath(row: firstAssetCellIndex, section: 0)
if let cell = collectionView.cellForItem(at: lastSelectedItemIndex!) as? DKAssetGroupDetailBaseCell, let asset = cell.asset {
if let highlightCallback = self.imagePickerController.didHighlightImage {
highlightCallback([asset])
}
cell.isCellFocused = true
}
/// Minimize the number of cycles.
let indexPathsForSelectedItems = collectionView.indexPathsForSelectedItems!
let indexPathsForVisibleItems = collectionView.indexPathsForVisibleItems
let intersect = Set(indexPathsForVisibleItems).intersection(Set(indexPathsForSelectedItems))
for selectedIndexPath in intersect {
if let selectedCell = (collectionView.cellForItem(at: selectedIndexPath) as? DKAssetGroupDetailBaseCell), let selectedCellAsset = selectedCell.asset, let selectedIndex = self.imagePickerController.selectedAssets.index(of: selectedCellAsset) {
if selectedIndex > removedIndex {
selectedCell.index = selectedCell.index - 1
}
}
}
collectionView.reloadData()
self.imagePickerController.deselectImage(removedAsset)
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.updateCachedAssets()
}
// MARK: - Asset Caching
var previousPreheatRect = CGRect.zero
fileprivate func resetCachedAssets() {
getImageManager().stopCachingForAllAssets()
self.previousPreheatRect = .zero
}
func updateCachedAssets() {
// Update only if the view is visible.
guard isViewLoaded && view.window != nil && self.selectedGroupId != nil else { return }
// The preheat window is twice the height of the visible rect.
let preheatRect = view!.bounds.insetBy(dx: 0, dy: -0.5 * view!.bounds.height)
// Update only if the visible area is significantly different from the last preheated area.
let delta = abs(preheatRect.midY - self.previousPreheatRect.midY)
guard delta > view.bounds.height / 3 else { return }
let group = getImageManager().groupDataManager.fetchGroupWithGroupId(self.selectedGroupId!)
// Compute the assets to start caching and to stop caching.
let (addedRects, removedRects) = self.differencesBetweenRects(self.previousPreheatRect, preheatRect)
let addedAssets = addedRects
.flatMap { rect in self.collectionView!.indexPathsForElements(in: rect, self.hidesCamera) }
.map { indexPath in getImageManager().groupDataManager.fetchOriginalAsset(group, index: indexPath.item) }
let removedAssets = removedRects
.flatMap { rect in self.collectionView!.indexPathsForElements(in: rect, self.hidesCamera) }
.map { indexPath in getImageManager().groupDataManager.fetchOriginalAsset(group, index: indexPath.item) }
// Update the assets the PHCachingImageManager is caching.
getImageManager().startCachingAssets(for: addedAssets,
targetSize: self.thumbnailSize, contentMode: .aspectFill, options: nil)
getImageManager().stopCachingAssets(for: removedAssets,
targetSize: self.thumbnailSize, contentMode: .aspectFill, options: nil)
// Store the preheat rect to compare against in the future.
self.previousPreheatRect = preheatRect
}
fileprivate func differencesBetweenRects(_ old: CGRect, _ new: CGRect) -> (added: [CGRect], removed: [CGRect]) {
if old.intersects(new) {
var added = [CGRect]()
if new.maxY > old.maxY {
added += [CGRect(x: new.origin.x, y: old.maxY,
width: new.width, height: new.maxY - old.maxY)]
}
if old.minY > new.minY {
added += [CGRect(x: new.origin.x, y: new.minY,
width: new.width, height: old.minY - new.minY)]
}
var removed = [CGRect]()
if new.maxY < old.maxY {
removed += [CGRect(x: new.origin.x, y: new.maxY,
width: new.width, height: old.maxY - new.maxY)]
}
if old.minY < new.minY {
removed += [CGRect(x: new.origin.x, y: old.minY,
width: new.width, height: new.minY - old.minY)]
}
return (added, removed)
} else {
return ([new], [old])
}
}
// MARK: - DKGroupDataManagerObserver methods
func groupDidUpdate(_ groupId: String) {
if self.selectedGroupId == groupId {
self.updateTitleView()
}
}
func group(_ groupId: String, didRemoveAssets assets: [DKAsset]) {
for (_, selectedAsset) in self.imagePickerController.selectedAssets.enumerated() {
for removedAsset in assets {
if selectedAsset.isEqual(removedAsset) {
self.imagePickerController.deselectImage(selectedAsset)
}
}
}
}
func groupDidUpdateComplete(_ groupId: String) {
if self.selectedGroupId == groupId {
self.resetCachedAssets()
self.collectionView?.reloadData()
}
}
}
| mit | 142504a10065d770ebe693f0042a06ee | 42.201245 | 270 | 0.682418 | 5.201849 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/Internal/Link/Verification/LinkVerificationController.swift | 1 | 1496 | //
// LinkVerificationController.swift
// StripePaymentSheet
//
// Created by Ramon Torres on 7/23/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import UIKit
/// Standalone verification controller.
final class LinkVerificationController {
typealias CompletionBlock = (LinkVerificationViewController.VerificationResult) -> Void
private var completion: CompletionBlock?
private var selfRetainer: LinkVerificationController?
private let verificationViewController: LinkVerificationViewController
init(mode: LinkVerificationView.Mode = .modal, linkAccount: PaymentSheetLinkAccount) {
self.verificationViewController = LinkVerificationViewController(mode: mode, linkAccount: linkAccount)
verificationViewController.delegate = self
}
func present(
from presentingController: UIViewController,
completion: @escaping CompletionBlock
) {
self.selfRetainer = self
self.completion = completion
presentingController.present(verificationViewController, animated: true)
}
}
extension LinkVerificationController: LinkVerificationViewControllerDelegate {
func verificationController(
_ controller: LinkVerificationViewController,
didFinishWithResult result: LinkVerificationViewController.VerificationResult
) {
controller.dismiss(animated: true) { [weak self] in
self?.completion?(result)
self?.selfRetainer = nil
}
}
}
| mit | 650cfc35098eab19f8435e285e63d98c | 29.510204 | 110 | 0.736455 | 5.516605 | false | false | false | false |
UW-AppDEV/AUXWave | AUXWave/PlaylistItem.swift | 1 | 3250 | //
// PlaylistItem.swift
// AUXWave
//
// Created by Nico Cvitak on 2015-03-13.
// Copyright (c) 2015 UW-AppDEV. All rights reserved.
//
import UIKit
import AVFoundation
import MediaPlayer
private var playlistItemImageCache: [String: UIImage] = [:]
extension MPMediaItem {
func asPlaylistItem() -> PlaylistItem {
let item = PlaylistItem(URL: self.assetURL)
item.title = self.title
item.artist = self.artist
item.albumName = self.albumTitle
let cacheID = "\(item.artist!) | \(item.albumName!)"
if let cached = playlistItemImageCache[cacheID] {
item.artwork = cached
} else if let artwork = self.artwork?.imageWithSize(kAlbumArtworkSize) {
playlistItemImageCache[cacheID] = artwork
item.artwork = artwork
}
return item
}
}
class PlaylistItem: AVPlayerItem {
class func clearImageCache() {
playlistItemImageCache.removeAll(keepCapacity: false)
}
lazy var title: String? = {
if let titleMetadataItem = AVMetadataItem.metadataItemsFromArray(self.asset.commonMetadata, withKey: AVMetadataCommonKeyTitle, keySpace: AVMetadataKeySpaceCommon).first as? AVMetadataItem {
return titleMetadataItem.value as? String
}
return nil
}()
lazy var artist: String? = {
if let artistMetadataItem = AVMetadataItem.metadataItemsFromArray(self.asset.commonMetadata, withKey: AVMetadataCommonKeyArtist, keySpace: AVMetadataKeySpaceCommon).first as? AVMetadataItem {
return artistMetadataItem.value as? String
}
return nil
}()
lazy var albumName: String? = {
if let albumNameMetadataItem = AVMetadataItem.metadataItemsFromArray(self.asset.commonMetadata, withKey: AVMetadataCommonKeyAlbumName, keySpace: AVMetadataKeySpaceCommon).first as? AVMetadataItem {
return albumNameMetadataItem.value as? String
}
return nil
}()
lazy var artwork: UIImage? = {
var cacheID: String = ""
if self.artist != nil && self.albumName != nil {
cacheID = "\(self.artist) | \(self.albumName)"
}
if let cached = playlistItemImageCache[cacheID] {
return cached
} else if let artworkMetadataItem = AVMetadataItem.metadataItemsFromArray(self.asset.commonMetadata, withKey: AVMetadataCommonKeyArtwork, keySpace: AVMetadataKeySpaceCommon).first as? AVMetadataItem {
if let artworkMetadataDictionary = artworkMetadataItem.value as? [String: AnyObject] {
if let artworkData = artworkMetadataDictionary["data"] as? NSData {
if let image = UIImage(data: artworkData) {
playlistItemImageCache[cacheID] = image
return image
}
}
} else if let artworkData = artworkMetadataItem.value as? NSData {
if let image = UIImage(data: artworkData) {
playlistItemImageCache[cacheID] = image
return image
}
}
}
return nil
}()
}
| gpl-2.0 | 40d8707e3db124224249d824bec77a7a | 34.326087 | 208 | 0.618462 | 4.916793 | false | false | false | false |
BerryMelon/Lineable | LineableLibrary/LineableConstants.swift | 1 | 1929 | //
// LineableConstants.swift
// LineableExample
//
// Created by Berrymelon on 2/17/16.
// Copyright © 2016 Lineable. All rights reserved.
//
import CoreBluetooth
let BLEServiceUUID = CBUUID(string: "955A1523-0FE2-F5AA-A094-84B8D4F3E8AD")
let MajorMinorCharUUID = CBUUID(string: "955A1526-0FE2-F5AA-A094-84B8D4F3E8AD")
let RssiCharUUID = CBUUID(string: "955A1525-0FE2-F5AA-A094-84B8D4F3E8AD")
let BeaconUUIDCharUUID = CBUUID(string: "955A1524-0FE2-F5AA-A094-84B8D4F3E8AD")
let VendorCharUUID = CBUUID(string: "955A1527-0FE2-F5AA-A094-84B8D4F3E8AD")
let LEDCharUUID = CBUUID(string: "955A1530-0FE2-F5AA-A094-84B8D4F3E8AD")
let SoundCharUUID = CBUUID(string: "955A1530-0FE2-F5AA-A094-84B8D4F3E8AD")
let FlashCharUUID = CBUUID(string: "955A1529-0FE2-F5AA-A094-84B8D4F3E8AD")
let SecurityCharUUID = CBUUID(string: "955A1529-0FE2-F5AA-A094-84B8D4F3E8AD")
let BatteryCharUUID = CBUUID(string: "955a1531-0fe2-f5aa-a094-84b8d4f3e8ad")
extension CBCharacteristic {
var string:String {
if self.UUID.UUIDString == BLEServiceUUID.UUIDString {
return "Ble Service UUID"
}
if self.UUID.UUIDString == RssiCharUUID.UUIDString {
return "RSSI"
}
if self.UUID.UUIDString == BeaconUUIDCharUUID.UUIDString {
return "UUID"
}
if self.UUID.UUIDString == VendorCharUUID.UUIDString {
return "Vendor"
}
if self.UUID.UUIDString == LEDCharUUID.UUIDString {
return "LED"
}
if self.UUID.UUIDString == FlashCharUUID.UUIDString {
return "Flash"
}
if self.UUID.UUIDString == SecurityCharUUID.UUIDString {
return "Security"
}
if self.UUID.UUIDString == BatteryCharUUID.UUIDString {
return "Battery"
}
return self.UUID.UUIDString
}
} | mit | a48cca9b35dcbb6c8ff8956a37d8aad6 | 30.622951 | 79 | 0.64834 | 3.0848 | false | false | false | false |
trill-lang/trill | Sources/Parse/BaseParser.swift | 2 | 11087 | ///
/// BaseParser.swift
///
/// Copyright 2016-2017 the Trill project authors.
/// Licensed under the MIT License.
///
/// Full license text available at https://github.com/trill-lang/trill
///
import AST
import Diagnostics
import Foundation
import Source
enum ParseError: Error, CustomStringConvertible {
case unexpectedToken(token: TokenKind)
case missingLineSeparator
case expectedIdentifier(got: TokenKind)
case duplicateDefault
case unexpectedExpression(expected: String)
case duplicateDeinit
case invalidAttribute(DeclModifier, DeclKind)
case duplicateSetter
case duplicateGetter
case computedPropertyRequiresType
case computedPropertyMustBeMutable
case globalSubscript
var description: String {
switch self {
case .unexpectedToken(let token):
return "unexpected token '\(token.text)'"
case .missingLineSeparator:
return "missing line separator"
case .expectedIdentifier(let got):
return "expected identifier (got '\(got.text)')"
case .duplicateDefault:
return "only one default statement is allowed in a switch"
case .unexpectedExpression(let expected):
return "unexpected expression (expected '\(expected)')"
case .duplicateDeinit:
return "cannot have multiple 'deinit's within a type"
case .invalidAttribute(let attr, let kind):
return "'\(attr)' is not valid on \(kind)s"
case .globalSubscript:
return "subscript is only valid inside a type"
case .duplicateSetter:
return "only one setter is allowed per property"
case .duplicateGetter:
return "only one getter is allowed per property"
case .computedPropertyRequiresType:
return "computed properties require an explicit type"
case .computedPropertyMustBeMutable:
return "computed property must be declared with 'var'"
}
}
}
public class Parser {
var tokenIndex = 0
var tokens: [Token]
let file: SourceFile
var filename: String { return file.path.filename }
let context: ASTContext
init(tokens: [Token], file: SourceFile, context: ASTContext) {
self.tokens = tokens
self.file = file
self.context = context
}
public static func parse(_ file: SourceFile, into context: ASTContext) {
do {
let fileContents = try context.sourceFileManager.contents(of: file)
var lexer = Lexer(file: file, input: fileContents)
let tokens = try lexer.lex()
let parser = Parser(tokens: tokens,
file: file,
context: context)
try parser.parseTopLevel(into: context)
} catch let diag as Diagnostic {
context.diag.add(diag)
} catch {
context.error(error)
}
}
func adjustedEnd() -> SourceLocation {
if (tokens.indices).contains(tokenIndex - 1) {
let t = tokens[tokenIndex - 1]
return t.range.end
} else {
return SourceLocation(line: 1, column: 1, file: file)
}
}
func missingLineSeparator() -> Error {
let end = adjustedEnd()
return Diagnostic.error(ParseError.missingLineSeparator,
loc: end)
}
func unexpectedToken() -> Error {
return Diagnostic.error(ParseError.unexpectedToken(token: peek()),
loc: currentToken().range.start,
highlights: [
currentToken().range
])
}
func attempt<T>(_ block: @autoclosure () throws -> T) throws -> T {
let startIndex = tokenIndex
do {
return try block()
} catch {
tokenIndex = startIndex
throw error
}
}
func range(start: SourceLocation) -> SourceRange {
let end: SourceLocation
if (tokens.indices).contains(tokenIndex - 1) {
let t = tokens[tokenIndex - 1]
end = t.range.end
} else {
end = start
}
return SourceRange(start: start, end: end)
}
var sourceLoc: SourceLocation {
return currentToken().range.start
}
func consume(_ token: TokenKind) throws {
guard token == peek() else {
throw unexpectedToken()
}
consumeToken()
}
func consumeAtLeastOneLineSeparator() throws {
if case .eof = peek() { return }
if [.newline, .semicolon].contains(peek()) {
consumeToken()
} else if ![.newline, .semicolon].contains(peek(ahead: -1)) {
throw missingLineSeparator()
}
consumeLineSeparators()
}
func consumeLineSeparators() {
while [.newline, .semicolon].contains(peek()) {
tokenIndex += 1
}
}
func comesAfterLineSeparator() -> Bool {
var n = -1
while case .semicolon = peek(ahead: n) {
n -= 1
}
return peek(ahead: n) == .newline
}
func peek(ahead offset: Int = 0) -> TokenKind {
let idx = tokenIndex + offset
guard tokens.indices.contains(idx) else {
return .eof
}
return tokens[idx].kind
}
func currentToken() -> Token {
guard tokens.indices.contains(tokenIndex) else {
let range = SourceRange(start: file.start, end: file.start)
return Token(kind: .eof,
range: range)
}
return tokens[tokenIndex]
}
@discardableResult
func consumeToken() -> Token {
let c = currentToken()
tokenIndex += 1
while case .newline = peek() {
tokenIndex += 1
}
return c
}
func backtrack(_ n: Int = 1) {
tokenIndex -= 1
}
func parseTopLevel(into context: ASTContext) throws {
while true {
consumeLineSeparators()
if case .eof = peek() {
break
}
let unexpected = {
throw Diagnostic.error(
ParseError.unexpectedExpression(expected: "function, type, or extension"),
loc: self.sourceLoc).highlighting(self.currentToken().range)
}
let modifiers: [DeclModifier]
do {
modifiers = try parseModifiers()
} catch {
try unexpected()
modifiers = []
}
switch peek() {
case .poundWarning, .poundError:
context.add(try parsePoundDiagnosticExpr())
case .func:
let decl = try parseFuncDecl(modifiers)
if let op = decl as? OperatorDecl {
context.add(op)
} else {
context.add(decl)
}
case .type:
let expr = try parseTypeDecl(modifiers)
if let typeDecl = expr as? TypeDecl {
context.add(typeDecl)
} else if let alias = expr as? TypeAliasDecl {
context.add(alias)
} else {
fatalError("non-type expr returned from parseTypeDecl()")
}
case .extension:
context.add(try parseExtensionDecl())
case .protocol:
context.add(try parseProtocolDecl(modifiers: modifiers))
case .var, .let:
context.add(try parseVarAssignDecl(modifiers: modifiers))
default:
try unexpected()
}
try consumeAtLeastOneLineSeparator()
}
}
func parseIdentifier() throws -> Identifier {
guard case .identifier(let name) = peek() else {
throw Diagnostic.error(ParseError.expectedIdentifier(got: peek()),
loc: sourceLoc)
}
return Identifier(name: name, range: consumeToken().range)
}
func parseModifiers() throws -> [DeclModifier] {
var attrs = [DeclModifier]()
while case .identifier(let attrId) = peek() {
if let attr = DeclModifier(rawValue: attrId) {
consumeToken()
attrs.append(attr)
} else {
throw Diagnostic.error(ParseError.expectedIdentifier(got: peek()),
loc: sourceLoc)
}
}
let nextKind: DeclKind
switch peek() {
case .func, .Init, .deinit, .operator, .subscript:
nextKind = .function
case .var, .let:
nextKind = .variable
case .type:
nextKind = .type
case .extension:
nextKind = .extension
case .protocol:
nextKind = .protocol
case .poundWarning, .poundError:
nextKind = .diagnostic
default:
throw unexpectedToken()
}
for attr in attrs {
if !attr.isValid(on: nextKind) {
throw Diagnostic.error(ParseError.invalidAttribute(attr, nextKind),
loc: sourceLoc)
}
}
return attrs
}
func parseExtensionDecl() throws -> ExtensionDecl {
let startLoc = sourceLoc
try consume(.extension)
let type = try parseType()
guard case .leftBrace = peek() else {
throw unexpectedToken()
}
consumeToken()
var methods = [MethodDecl]()
var staticMethods = [MethodDecl]()
var subscripts = [SubscriptDecl]()
while true {
if case .rightBrace = peek() {
consumeToken()
break
}
let attrs = try parseModifiers()
switch peek() {
case .func:
let decl = try parseFuncDecl(attrs, forType: type.type) as! MethodDecl
if attrs.contains(.static) {
staticMethods.append(decl)
} else {
methods.append(decl)
}
case .subscript:
subscripts.append(try parseFuncDecl(attrs, forType: type.type) as! SubscriptDecl)
default:
throw Diagnostic.error(ParseError.unexpectedExpression(expected: "function or subscript"),
loc: sourceLoc)
}
}
return ExtensionDecl(type: type,
methods: methods,
staticMethods: staticMethods,
subscripts: subscripts,
sourceRange: range(start: startLoc))
}
/// Compound Statement
///
/// { [<stmt>]* }
func parseCompoundStmt(leftBraceOptional: Bool = false) throws -> CompoundStmt {
let startLoc = sourceLoc
if leftBraceOptional {
if case .leftBrace = peek() {
consumeToken()
}
} else {
try consume(.leftBrace)
}
let stmts = try parseStatements(terminators: [.rightBrace])
consumeToken()
return CompoundStmt(stmts: stmts, sourceRange: range(start: startLoc))
}
func parseStatements(terminators: [TokenKind]) throws -> [Stmt] {
var stmts = [Stmt]()
while !terminators.contains(peek()) {
let stmt = try parseStatement()
if !terminators.contains(peek()) {
try consumeAtLeastOneLineSeparator()
}
if let diag = stmt as? PoundDiagnosticStmt {
context.add(diag)
} else {
stmts.append(stmt)
}
}
return stmts
}
func parseStatement() throws -> Stmt {
let tok = peek()
switch tok {
case .if:
return try parseIfExpr()
case .while:
return try parseWhileExpr()
case .for:
return try parseForLoopExpr()
case .switch:
return try parseSwitchExpr()
case .var, .let:
return DeclStmt(decl: try parseVarAssignDecl())
case .break:
return try parseBreakStmt()
case .continue:
return try parseContinueStmt()
case .return:
return try parseReturnStmt()
case .poundError, .poundWarning:
return try parsePoundDiagnosticExpr()
default:
return ExprStmt(expr: try parseValExpr())
}
}
}
| mit | 3b4b6f91e75ddcb09c2383a6a5110498 | 27.501285 | 98 | 0.611707 | 4.490482 | false | false | false | false |
wind3110991/2048 | swift-2048/Views/TileView.swift | 2 | 1231 | //
// TileView.swift
// swift-2048
//
// Created by Austin Zheng on 6/3/14.
// Copyright (c) 2014 Austin Zheng. All rights reserved.
//
import UIKit
/// A view representing a single swift-2048 tile.
class TileView : UIView {
// This should be unowned. But there is a bug preventing 'unowned' from working correctly with protocols.
var delegate: AppearanceProviderProtocol
var value: Int = 0 {
didSet {
backgroundColor = delegate.tileColor(value)
numberLabel.textColor = delegate.numberColor(value)
numberLabel.text = "\(value)"
}
}
var numberLabel: UILabel
init(position: CGPoint, width: CGFloat, value: Int, radius: CGFloat, delegate d: AppearanceProviderProtocol) {
delegate = d
numberLabel = UILabel(frame: CGRectMake(0, 0, width, width))
numberLabel.textAlignment = NSTextAlignment.Center
numberLabel.minimumScaleFactor = 0.5
numberLabel.font = delegate.fontForNumbers()
super.init(frame: CGRectMake(position.x, position.y, width, width))
addSubview(numberLabel)
layer.cornerRadius = radius
self.value = value
backgroundColor = delegate.tileColor(value)
numberLabel.textColor = delegate.numberColor(value)
numberLabel.text = "\(value)"
}
}
| mit | ef28082aecda0f4e987f0a608f44900f | 29.775 | 112 | 0.716491 | 4.274306 | false | false | false | false |
ifeherva/HSTracker | HSTracker/Logging/Enums/GameTag.swift | 1 | 9679 | /*
* This file is part of the HSTracker package.
* (c) Benjamin Michotte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Created on 19/02/16.
*/
import Foundation
import Wrap
enum GameTag: Int, WrappableEnum, EnumCollection {
case ignore_damage = 1,
tag_script_data_num_1 = 2,
tag_script_data_num_2 = 3,
tag_script_data_ent_1 = 4,
tag_script_data_ent_2 = 5,
mission_event = 6,
timeout = 7,
turn_start = 8,
turn_timer_slush = 9,
premium = 12,
gold_reward_state = 13,
playstate = 17,
last_affected_by = 18,
step = 19,
turn = 20,
fatigue = 22,
current_player = 23,
first_player = 24,
resources_used = 25,
resources = 26,
hero_entity = 27,
maxhandsize = 28,
starthandsize = 29,
player_id = 30,
team_id = 31,
trigger_visual = 32,
recently_arrived = 33,
protected = 34,
protecting = 35,
defending = 36,
proposed_defender = 37,
attacking = 38,
proposed_attacker = 39,
attached = 40,
exhausted = 43,
damage = 44,
health = 45,
atk = 47,
cost = 48,
zone = 49,
controller = 50,
owner = 51,
definition = 52,
entity_id = 53,
history_proxy = 54,
copy_deathrattle = 55,
copy_deathrattle_index = 56,
elite = 114,
maxresources = 176,
card_set = 183,
cardtext_inhand = 184,
cardname = 185,
card_id = 186,
durability = 187,
silenced = 188,
windfury = 189,
taunt = 190,
stealth = 191,
spellpower = 192,
divine_shield = 194,
charge = 197,
next_step = 198,
`class` = 199,
cardrace = 200,
faction = 201,
cardtype = 202,
rarity = 203,
state = 204,
summoned = 205,
freeze = 208,
enraged = 212,
//overload = 215,
recall = 215,
loyalty = 216,
deathrattle = 217,
//death_rattle = 217,
battlecry = 218,
secret = 219,
combo = 220,
cant_heal = 221,
cant_damage = 222,
cant_set_aside = 223,
cant_remove_from_game = 224,
cant_ready = 225,
cant_exhaust = 226,
cant_attack = 227,
cant_target = 228,
cant_destroy = 229,
cant_discard = 230,
cant_play = 231,
cant_draw = 232,
incoming_healing_multiplier = 233,
incoming_healing_adjustment = 234,
incoming_healing_cap = 235,
incoming_damage_multiplier = 236,
incoming_damage_adjustment = 237,
incoming_damage_cap = 238,
cant_be_healed = 239,
//immune = 240,
cant_be_damaged = 240,
cant_be_set_aside = 241,
cant_be_removed_from_game = 242,
cant_be_readied = 243,
cant_be_exhausted = 244,
cant_be_attacked = 245,
cant_be_targeted = 246,
cant_be_destroyed = 247,
attackvisualtype = 251,
cardtextinplay = 252,
cant_be_summoning_sick = 253,
frozen = 260,
just_played = 261,
linkedcard = 262,
//linked_entity = 262,
zone_position = 263,
cant_be_frozen = 264,
combo_active = 266,
card_target = 267,
devstate = 268,
num_cards_played_this_turn = 269,
cant_be_targeted_by_opponents = 270,
num_turns_in_play = 271,
num_turns_left = 272,
outgoing_damage_cap = 273,
outgoing_damage_adjustment = 274,
outgoing_damage_multiplier = 275,
outgoing_healing_cap = 276,
outgoing_healing_adjustment = 277,
outgoing_healing_multiplier = 278,
incoming_ability_damage_adjustment = 279,
incoming_combat_damage_adjustment = 280,
outgoing_ability_damage_adjustment = 281,
outgoing_combat_damage_adjustment = 282,
outgoing_ability_damage_multiplier = 283,
outgoing_ability_damage_cap = 284,
incoming_ability_damage_multiplier = 285,
incoming_ability_damage_cap = 286,
outgoing_combat_damage_multiplier = 287,
outgoing_combat_damage_cap = 288,
incoming_combat_damage_multiplier = 289,
incoming_combat_damage_cap = 290,
current_spellpower = 291,
armor = 292,
morph = 293,
is_morphed = 294,
temp_resources = 295,
//overload_owed = 296,
recall_owed = 296,
num_attacks_this_turn = 297,
next_ally_buff = 302,
magnet = 303,
first_card_played_this_turn = 304,
mulligan_state = 305,
taunt_ready = 306,
stealth_ready = 307,
charge_ready = 308,
cant_be_targeted_by_abilities = 311,
//cant_be_targeted_by_spells = 311,
shouldexitcombat = 312,
creator = 313,
//cant_be_dispelled = 314,
divine_shield_ready = 314,
//cant_be_silenced = 314,
parent_card = 316,
num_minions_played_this_turn = 317,
predamage = 318,
collectible = 321,
targeting_arrow_text = 325,
enchantment_birth_visual = 330,
enchantment_idle_visual = 331,
cant_be_targeted_by_hero_powers = 332,
weapon = 334,
invisibledeathrattle = 335,
health_minimum = 337,
tag_one_turn_effect = 338,
silence = 339,
counter = 340,
artistname = 342,
localizationnotes = 344,
hand_revealed = 348,
immunetospellpower = 349,
adjacent_buff = 350,
flavortext = 351,
forced_play = 352,
low_health_threshold = 353,
ignore_damage_off = 354,
grantcharge = 355,
spellpower_double = 356,
healing_double = 357,
num_options_played_this_turn = 358,
num_options = 359,
to_be_destroyed = 360,
healtarget = 361,
aura = 362,
poisonous = 363,
how_to_earn = 364,
how_to_earn_golden = 365,
tag_hero_power_double = 366,
//hero_power_double = 366,
//ai_must_play = 367,
tag_ai_must_play = 367,
num_minions_player_killed_this_turn = 368,
num_minions_killed_this_turn = 369,
affected_by_spell_power = 370,
extra_deathrattles = 371,
start_with_1_health = 372,
immune_while_attacking = 373,
multiply_hero_damage = 374,
multiply_buff_value = 375,
custom_keyword_effect = 376,
topdeck = 377,
cant_be_targeted_by_battlecries = 379,
hero_power = 380,
//overkill = 380,
//shown_hero_power = 380,
deathrattle_sends_back_to_deck = 382,
//deathrattle_return_zone = 382,
steady_shot_can_target = 383,
displayed_creator = 385,
powered_up = 386,
spare_part = 388,
forgetful = 389,
can_summon_maxplusone_minion = 390,
obfuscated = 391,
burning = 392,
overload_locked = 393,
num_times_hero_power_used_this_game = 394,
current_heropower_damage_bonus = 395,
heropower_damage = 396,
last_card_played = 397,
num_friendly_minions_that_died_this_turn = 398,
num_cards_drawn_this_turn = 399,
ai_one_shot_kill = 400,
evil_glow = 401,
//hide_cost = 402,
hide_stats = 402,
inspire = 403,
receives_double_spelldamage_bonus = 404,
heropower_additional_activations = 405,
heropower_activations_this_turn = 406,
revealed = 410,
num_friendly_minions_that_died_this_game = 412,
cannot_attack_heroes = 413,
lock_and_load = 414,
//discover = 415,
treasure = 415,
shadowform = 416,
num_friendly_minions_that_attacked_this_turn = 417,
num_resources_spent_this_game = 418,
choose_both = 419,
electric_charge_level = 420,
heavily_armored = 421,
dont_show_immune = 422,
ritual = 424,
prehealing = 425,
appear_functionally_dead = 426,
overload_this_game = 427,
spells_cost_health = 431,
history_proxy_no_big_card = 432,
proxy_cthun = 434,
transformed_from_card = 435,
cthun = 436,
cast_random_spells = 437,
shifting = 438,
jade_golem = 441,
embrace_the_shadow = 442,
choose_one = 443,
extra_attacks_this_turn = 444,
seen_cthun = 445,
minion_type_reference = 447,
untouchable = 448,
red_mana_crystals = 449,
score_labelid_1 = 450,
score_value_1 = 451,
score_labelid_2 = 452,
score_value_2 = 453,
score_labelid_3 = 454,
score_value_3 = 455,
cant_be_fatigued = 456,
autoattack = 457,
arms_dealing = 458,
pending_evolutions = 461,
quest = 462,
tag_last_known_cost_in_hand = 466,
defining_enchantment = 469,
finish_attack_spell_on_damage = 470,
kazakus_potion_power_1 = 471,
kazakus_potion_power_2 = 472,
modify_definition_attack = 473,
modify_definition_health = 474,
modify_definition_cost = 475,
multiple_classes = 476,
all_targets_random = 477,
multi_class_group = 480,
card_costs_health = 481,
grimy_goons = 482,
jade_lotus = 483,
kabal = 484,
additional_play_reqs_1 = 515,
additional_play_reqs_2 = 516,
elemental_powered_up = 532,
quest_progress = 534,
quest_progress_total = 535,
quest_contributor = 541,
adapt = 546,
is_current_turn_an_extra_turn = 547,
extra_turns_taken_this_game = 548,
shifting_minion = 549,
shifting_weapon = 550,
death_knight = 554,
boss = 556,
stampede = 564,
is_vampire = 680,
corrupted = 681,
lifesteal = 685,
override_emote_0 = 740,
override_emote_1 = 741,
override_emote_2 = 742,
override_emote_3 = 743,
override_emote_4 = 744,
override_emote_5 = 745,
score_footerid = 751,
hero_power_disabled = 777,
valeerashadow = 779,
overridecardname = 781,
overridecardtextbuilder = 782,
hidden_choice = 813,
zombeast = 823
init?(rawString: String) {
let string = rawString.lowercased()
for _enum in GameTag.cases() where "\(_enum)" == string {
self = _enum
return
}
if let value = Int(rawString), let _enum = GameTag(rawValue: value) {
self = _enum
return
}
return nil
}
}
| mit | b71ce64a2e8775e48f2437f0e484fe92 | 26.188202 | 77 | 0.614423 | 3.220965 | false | false | false | false |
alitan2014/swift | Heath/Heath/Controllers/MyDoctorViewController.swift | 1 | 2897 | //
// MyDoctorViewController.swift
// Heath
//
// Created by TCL on 15/7/14.
// Copyright (c) 2015年 Mac. All rights reserved.
//
import UIKit
class MyDoctorViewController: UIViewController {
@IBOutlet weak var bgImgView: UIImageView!
@IBOutlet weak var serverLabel: UILabel!
@IBOutlet weak var outLineLabel: UILabel!
@IBOutlet weak var heathServerLabel: UILabel!
@IBOutlet weak var niceLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
createUI()
// Do any additional setup after loading the view.
}
func createUI()
{
self.serverLabel.textColor=UIColor(red: 251/255.0, green: 78/255.0, blue: 10/255.0, alpha: 1)
self.outLineLabel.textColor=UIColor(red: 251/255.0, green: 78/255.0, blue: 10/255.0, alpha: 1)
self.heathServerLabel.textColor=UIColor(red: 251/255.0, green: 78/255.0, blue: 10/255.0, alpha: 1)
self.niceLabel.textColor=UIColor(red: 251/255.0, green: 78/255.0, blue: 10/255.0, alpha: 1)
}
@IBAction func btnClick(sender: AnyObject) {
var tag = sender.tag
switch tag
{
case 10 ://你点击了QQ
println("你点击了QQ")
case 20 ://你点击了电话
println("你点击了电话")
case 30 ://你点击了手机
println("你点击了手机")
case 40 ://你点击了预约挂号
var reservation = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ReservationController") as! ReservationController
self.tabBarController?.tabBar.hidden=true
self.navigationController?.pushViewController(reservation, animated: true)
println("你点击了预约挂号")
case 50 ://你点击了健康顾问
println("你点击了健康顾问")
case 60 ://你点击了离线回答
println("你点击了离线回答")
case 70 ://你点击了消息
println("你点击了消息")
default :
println("你点击了其他")
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: true)
self.tabBarController?.tabBar.hidden=false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
}
| gpl-2.0 | 1bff0f69e25a3a56618d236414b6695d | 31.518072 | 160 | 0.632086 | 4.152308 | false | false | false | false |
christophhagen/Signal-iOS | Signal/src/util/TextFieldHelper.swift | 1 | 2151 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import UIKit
@objc class TextFieldHelper: NSObject {
// Used to implement the UITextFieldDelegate method: `textField:shouldChangeCharactersInRange:replacementString`
// Takes advantage of Swift's superior unicode handling to append partial pasted text without splitting multi-byte characters.
class func textField(_ textField: UITextField, shouldChangeCharactersInRange editingRange: NSRange, replacementString: String, byteLimit: UInt) -> Bool {
let byteLength = { (string: String) -> UInt in
return UInt(string.utf8.count)
}
let existingString = textField.text ?? ""
// Given an NSRange, we need to interact with the NS flavor of substring
let removedString = (existingString as NSString).substring(with: editingRange)
let lengthOfRemainingExistingString = byteLength(existingString) - byteLength(removedString)
let newLength = lengthOfRemainingExistingString + byteLength(replacementString)
if (newLength <= byteLimit) {
return true
}
// Don't allow any change if inserting a single char is already over the limit (typically this means typing)
if (replacementString.count < 2) {
return false
}
// However if pasting, accept as much of the string as possible.
let availableSpace = byteLimit - lengthOfRemainingExistingString
var acceptableSubstring = ""
for (_, char) in replacementString.characters.enumerated() {
var maybeAcceptableSubstring = acceptableSubstring
maybeAcceptableSubstring.append(char)
if (byteLength(maybeAcceptableSubstring) <= availableSpace) {
acceptableSubstring = maybeAcceptableSubstring
} else {
break
}
}
textField.text = (existingString as NSString).replacingCharacters(in: editingRange, with:acceptableSubstring)
// We've already handled any valid editing manually, so prevent further changes.
return false
}
}
| gpl-3.0 | 8885e6c060d3266ce553b98e9d13b3ff | 37.410714 | 157 | 0.683403 | 5.404523 | false | false | false | false |
Zewo/Zewo | Sources/Media/Media/Coding.swift | 1 | 1604 | enum MapSuperKey : String, CodingKey {
case `super`
}
extension String : CodingKey {
public var stringValue: String {
return self
}
public init?(stringValue: String) {
self = stringValue
}
public var intValue: Int? {
return Int(self)
}
public init?(intValue: Int) {
self = String(intValue)
}
}
extension Int : CodingKey {
public var stringValue: String {
return String(self)
}
public init?(stringValue: String) {
guard let int = Int(stringValue) else {
return nil
}
self = int
}
public var intValue: Int? {
return self
}
public init?(intValue: Int) {
self = intValue
}
}
extension EncodingError.Context {
public init(codingPath: [CodingKey] = []) {
self.init(
codingPath: codingPath,
debugDescription: "",
underlyingError: nil
)
}
public init(debugDescription: String) {
self.init(
codingPath: [],
debugDescription: debugDescription,
underlyingError: nil
)
}
}
extension DecodingError.Context {
public init(codingPath: [CodingKey] = []) {
self.init(
codingPath: codingPath,
debugDescription: "",
underlyingError: nil
)
}
public init(debugDescription: String) {
self.init(
codingPath: [],
debugDescription: debugDescription,
underlyingError: nil
)
}
}
| mit | d0af699d37e9c1388903403fcd0fbcd9 | 19.303797 | 47 | 0.530549 | 5.044025 | false | false | false | false |
rhx/gir2swift | Sources/libgir2swift/models/gir elements/GirDatatype.swift | 1 | 2779 | //
// File.swift
//
//
// Created by Mikoláš Stuchlík on 17.11.2020.
//
import SwiftLibXML
extension GIR {
/// GIR type class
public class Datatype: Thing {
/// String representation of the `Datatype` thing
public override var kind: String { return "Datatype" }
/// The underlying type
public var typeRef: TypeReference
/// The identifier of this instance (e.g. C enum value type)
@inlinable public var identifier: String? { typeRef.identifier }
/// A reference to the underlying C type
@inlinable public var underlyingCRef: TypeReference {
let type = typeRef.type
let nm = typeRef.fullCType
let tp = GIRType(name: nm, ctype: type.ctype, superType: type.parent, isAlias: type.isAlias, conversions: type.conversions)
let ref = TypeReference(type: tp, identifier: typeRef.identifier, isConst: typeRef.isConst, isOptional: typeRef.isOptional, isArray: typeRef.isArray, constPointers: typeRef.constPointers)
return ref
}
/// Memberwise initialiser
/// - Parameters:
/// - name: The name of the `Datatype` to initialise
/// - type: The corresponding, underlying GIR type
/// - comment: Documentation text for the data type
/// - introspectable: Set to `true` if introspectable
/// - deprecated: Documentation on deprecation status if non-`nil`
/// - version: The version this data type is first available in
public init(name: String, type: TypeReference, comment: String, introspectable: Bool = false, deprecated: String? = nil) {
typeRef = type
super.init(name: name, comment: comment, introspectable: introspectable, deprecated: deprecated)
registerKnownType()
}
/// XML Element initialser
/// - Parameters:
/// - node: `XMLElement` to construct this data type from
/// - index: Index within the siblings of the `node`
/// - type: Type reference for the data type (taken from XML if `nil`)
/// - nameAttr: Key for the attribute to extract the `name` property from
public init(node: XMLElement, at index: Int, with type: TypeReference? = nil, nameAttr: String = "name") {
typeRef = type ?? node.alias
super.init(node: node, at: index, nameAttr: nameAttr)
typeRef.isArray = node.name == "array"
registerKnownType()
}
/// Register this type as an enumeration type
@inlinable
public func registerKnownType() {
}
/// Returns `true` if the data type is `void`
public var isVoid: Bool {
return typeRef.isVoid
}
}
}
| bsd-2-clause | 22293ea0520f2942dc30e5612d2ff623 | 41.060606 | 199 | 0.613833 | 4.565789 | false | false | false | false |
ccrama/Slide-iOS | Slide for Reddit/ProfileViewController.swift | 1 | 17301 | //
// MainViewController.swift
// Slide for Reddit
//
// Created by Carlos Crane on 1/4/17.
// Copyright © 2016 Haptic Apps. All rights reserved.
//
import Anchorage
import MaterialComponents.MDCTabBar
import MKColorPicker
import reddift
import RLBAlertsPickers
import SDCAlertView
import UIKit
class ProfileViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, ColorPickerViewDelegate, UIScrollViewDelegate {
var content: [UserContent] = []
var name: String = ""
var isReload = false
var session: Session?
var vCs: [UIViewController] = []
var openTo = 0
var newColor = UIColor.white
var friends = false
public func colorPickerView(_ colorPickerView: ColorPickerView, didSelectItemAt indexPath: IndexPath) {
newColor = colorPickerView.colors[indexPath.row]
self.navigationController?.navigationBar.barTintColor = SettingValues.reduceColor ? ColorUtil.theme.backgroundColor : colorPickerView.colors[indexPath.row]
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if ColorUtil.theme.isLight && SettingValues.reduceColor {
if #available(iOS 13, *) {
return .darkContent
} else {
return .default
}
} else {
return .lightContent
}
}
func pickColor(sender: AnyObject) {
if #available(iOS 14, *) {
let picker = UIColorPickerViewController()
picker.title = "Profile color"
picker.supportsAlpha = false
picker.selectedColor = ColorUtil.getColorForUser(name: name)
picker.delegate = self
present(picker, animated: true)
} else {
let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
let margin: CGFloat = 10.0
let rect = CGRect(x: margin, y: margin, width: UIScreen.main.traitCollection.userInterfaceIdiom == .pad ? 314 - margin * 4.0: alertController.view.bounds.size.width - margin * 4.0, height: 150)
let MKColorPicker = ColorPickerView.init(frame: rect)
MKColorPicker.delegate = self
MKColorPicker.colors = GMPalette.allColor()
MKColorPicker.selectionStyle = .check
MKColorPicker.scrollDirection = .vertical
MKColorPicker.style = .circle
alertController.view.addSubview(MKColorPicker)
let somethingAction = UIAlertAction(title: "Save", style: .default, handler: {(_: UIAlertAction!) in
ColorUtil.setColorForUser(name: self.name, color: self.newColor)
})
alertController.addAction(somethingAction)
alertController.addCancelButton()
alertController.modalPresentationStyle = .popover
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = (moreB!.value(forKey: "view") as! UIView)
presenter.sourceRect = (moreB!.value(forKey: "view") as! UIView).bounds
}
alertController.modalPresentationStyle = .popover
if let presenter = alertController.popoverPresentationController {
presenter.sourceView = sender as! UIButton
presenter.sourceRect = (sender as! UIButton).bounds
}
present(alertController, animated: true, completion: nil)
}
}
var tagText: String?
func tagUser() {
let alert = DragDownAlertMenu(title: AccountController.formatUsername(input: name, small: true), subtitle: "Tag profile", icon: nil, full: true)
alert.addTextInput(title: "Set tag", icon: UIImage(sfString: SFSymbol.tagFill, overrideString: "save-1")?.menuIcon(), action: {
alert.dismiss(animated: true) { [weak self] in
guard let self = self else { return }
ColorUtil.setTagForUser(name: self.name, tag: alert.getText() ?? "")
}
}, inputPlaceholder: "Enter a tag...", inputValue: ColorUtil.getTagForUser(name: name), inputIcon: UIImage(sfString: SFSymbol.tagFill, overrideString: "subs")!.menuIcon(), textRequired: true, exitOnAction: true)
if !(ColorUtil.getTagForUser(name: name) ?? "").isEmpty {
alert.addAction(title: "Remove tag", icon: UIImage(sfString: SFSymbol.trashFill, overrideString: "delete")?.menuIcon(), enabled: true) {
ColorUtil.removeTagForUser(name: self.name)
}
}
alert.show(self)
}
init(name: String) {
self.name = name
self.session = (UIApplication.shared.delegate as! AppDelegate).session
if let n = (session?.token.flatMap { (token) -> String? in
return token.name
}) as String? {
if name == n {
friends = true
self.content = [.overview, .submitted, .comments, .liked, .saved, .disliked, .hidden, .gilded]
} else {
self.content = ProfileViewController.doDefault()
}
} else {
self.content = ProfileViewController.doDefault()
}
if friends {
self.vCs.append(ContentListingViewController.init(dataSource: FriendsContributionLoader.init()))
}
for place in content {
self.vCs.append(ContentListingViewController.init(dataSource: ProfileContributionLoader.init(name: name, whereContent: place)))
}
tabBar = MDCTabBar()
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
let sort = UIButton.init(type: .custom)
sort.setImage(UIImage(sfString: SFSymbol.arrowUpArrowDownCircle, overrideString: "ic_sort_white")?.navIcon(), for: UIControl.State.normal)
sort.addTarget(self, action: #selector(self.showSortMenu(_:)), for: UIControl.Event.touchUpInside)
sort.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
sortB = UIBarButtonItem.init(customView: sort)
let more = UIButton.init(type: .custom)
more.setImage(UIImage(sfString: SFSymbol.infoCircle, overrideString: "info")?.navIcon(), for: UIControl.State.normal)
more.addTarget(self, action: #selector(self.showMenu(_:)), for: UIControl.Event.touchUpInside)
more.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
moreB = UIBarButtonItem.init(customView: more)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
static func doDefault() -> [UserContent] {
return [UserContent.overview, UserContent.comments, UserContent.submitted, UserContent.gilded]
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
var moreB: UIBarButtonItem?
var sortB: UIBarButtonItem?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.title = AccountController.formatUsername(input: name, small: true)
navigationController?.navigationBar.isTranslucent = false
self.navigationController?.setNavigationBarHidden(false, animated: true)
if navigationController != nil {
navigationController?.navigationBar.barTintColor = ColorUtil.getColorForSub(sub: "", true)
navigationController?.navigationBar.tintColor = SettingValues.reduceColor ? ColorUtil.theme.fontColor : UIColor.white
}
if navigationController != nil {
self.navigationController?.navigationBar.shadowImage = UIImage()
}
}
lazy var currentAccountTransitioningDelegate = ProfileInfoPresentationManager()
func showMenu(sender: AnyObject, user: String) {
let vc = ProfileInfoViewController(accountNamed: user, parent: self)
vc.modalPresentationStyle = .custom
vc.transitioningDelegate = currentAccountTransitioningDelegate
present(vc, animated: true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.setupBaseBarColors()
}
func close() {
navigationController?.popViewController(animated: true)
}
var tabBar: MDCTabBar
override func viewDidLoad() {
super.viewDidLoad()
if let navigationController = navigationController {
if navigationController.viewControllers.count == 1 {
navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "Close", style: .done, target: self, action: #selector(closeButtonPressed))
}
}
view.backgroundColor = ColorUtil.theme.backgroundColor
var items: [String] = []
if friends {
items.append("FRIENDS")
}
for i in content {
items.append(i.title)
}
tabBar = MDCTabBar.init(frame: CGRect.zero)
tabBar.itemAppearance = .titles
tabBar.items = items.enumerated().map { index, source in
return UITabBarItem(title: source, image: nil, tag: index)
}
tabBar.backgroundColor = ColorUtil.getColorForSub(sub: "", true)
tabBar.selectedItemTintColor = (SettingValues.reduceColor ? ColorUtil.theme.fontColor : UIColor.white)
tabBar.unselectedItemTintColor = (SettingValues.reduceColor ? ColorUtil.theme.fontColor : UIColor.white).withAlphaComponent(0.45)
if friends {
openTo += 1
}
currentIndex = openTo
tabBar.selectedItem = tabBar.items[openTo]
tabBar.delegate = self
tabBar.inkColor = UIColor.clear
tabBar.tintColor = ColorUtil.accentColorForSub(sub: "NONE")
self.view.addSubview(tabBar)
tabBar.heightAnchor == 48
tabBar.horizontalAnchors == self.view.horizontalAnchors
self.edgesForExtendedLayout = UIRectEdge.all
self.extendedLayoutIncludesOpaqueBars = true
self.automaticallyAdjustsScrollViewInsets = false
var isModal13 = false
if #available(iOS 13, *), self.presentingViewController != nil && (self.navigationController?.modalPresentationStyle == .formSheet || self.modalPresentationStyle == .formSheet || self.navigationController?.modalPresentationStyle == .pageSheet || self.modalPresentationStyle == .pageSheet) {
isModal13 = true
}
let topAnchorOffset = (self.navigationController?.navigationBar.frame.size.height ?? 64) + (isModal13 ? 0 : UIApplication.shared.statusBarFrame.height)
if #available(iOS 13, *) {
tabBar.topAnchor == self.view.topAnchor + topAnchorOffset
} else {
tabBar.topAnchor == self.view.topAnchor
}
tabBar.sizeToFit()
self.dataSource = self
self.delegate = self
self.navigationController?.view.backgroundColor = UIColor.clear
let firstViewController = vCs[openTo]
for view in view.subviews {
if view is UIScrollView {
(view as! UIScrollView).delegate = self
break
}
}
if self.navigationController?.interactivePopGestureRecognizer != nil {
for view in view.subviews {
if let scrollView = view as? UIScrollView {
scrollView.panGestureRecognizer.require(toFail: self.navigationController!.interactivePopGestureRecognizer!)
scrollView.delegate = self
}
}
}
setViewControllers([firstViewController],
direction: .forward,
animated: true,
completion: nil)
self.currentVc = vCs[openTo]
let current = content[openTo]
if current == .comments || current == .submitted || current == .overview {
navigationItem.rightBarButtonItems = [ moreB!, sortB!]
} else {
navigationItem.rightBarButtonItems = [ moreB!]
}
}
var currentVc = UIViewController()
@objc func showSortMenu(_ sender: UIButton?) {
(self.currentVc as? ContentListingViewController)?.showSortMenu(sender)
}
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = vCs.firstIndex(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
guard vCs.count > previousIndex else {
return nil
}
return vCs[previousIndex]
}
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = vCs.firstIndex(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
let orderedViewControllersCount = vCs.count
guard orderedViewControllersCount != nextIndex else {
return nil
}
guard orderedViewControllersCount > nextIndex else {
return nil
}
return vCs[nextIndex]
}
@objc func showMenu(_ sender: AnyObject) {
self.showMenu(sender: sender, user: self.name)
}
var selected = false
func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
guard completed else { return }
let page = vCs.firstIndex(of: self.viewControllers!.first!)
tabBar.setSelectedItem(tabBar.items[page! ], animated: true)
currentVc = self.viewControllers!.first!
currentIndex = page!
let contentIndex = page! - (friends ? 1 : 0)
if contentIndex >= 0 {
let current = content[contentIndex]
if current == .comments || current == .submitted || current == .overview {
navigationItem.rightBarButtonItems = [ moreB!, sortB!]
} else {
navigationItem.rightBarButtonItems = [ moreB!]
}
} else {
navigationItem.rightBarButtonItems = [ moreB!]
}
}
var currentIndex = 0
var lastPosition: CGFloat = 0
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.lastPosition = scrollView.contentOffset.x
if currentIndex == 0 && scrollView.contentOffset.x < scrollView.bounds.size.width {
scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0)
} else if currentIndex == vCs.count - 1 && scrollView.contentOffset.x > scrollView.bounds.size.width {
scrollView.contentOffset = CGPoint(x: scrollView.bounds.size.width, y: 0)
}
}
//From https://stackoverflow.com/a/25167681/3697225
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
if currentIndex == 0 && scrollView.contentOffset.x <= scrollView.bounds.size.width {
targetContentOffset.pointee = CGPoint(x: scrollView.bounds.size.width, y: 0)
} else if currentIndex == vCs.count - 1 && scrollView.contentOffset.x >= scrollView.bounds.size.width {
targetContentOffset.pointee = CGPoint(x: scrollView.bounds.size.width, y: 0)
}
}
}
extension ProfileViewController: MDCTabBarDelegate {
func tabBar(_ tabBar: MDCTabBar, didSelect item: UITabBarItem) {
selected = true
let firstViewController = vCs[tabBar.items.firstIndex(of: item)!]
currentIndex = tabBar.items.firstIndex(of: item)!
currentVc = firstViewController
let contentIndex = currentIndex - (friends ? 1 : 0)
if contentIndex >= 0 {
let current = content[contentIndex]
if current == .comments || current == .overview || current == .submitted {
navigationItem.rightBarButtonItems = [ moreB!, sortB!]
} else {
navigationItem.rightBarButtonItems = [ moreB!]
}
}
setViewControllers([firstViewController],
direction: .forward,
animated: false,
completion: nil)
}
}
// MARK: - Actions
extension ProfileViewController {
@objc func closeButtonPressed() {
dismiss(animated: true, completion: nil)
}
}
@available(iOS 14.0, *)
extension ProfileViewController: UIColorPickerViewControllerDelegate {
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
newColor = viewController.selectedColor
}
}
| apache-2.0 | 3df7cc9798d31d4b9dc509aba4124850 | 39.232558 | 298 | 0.628208 | 5.206139 | false | false | false | false |
nRewik/swift-corelibs-foundation | TestFoundation/TestNSSet.swift | 1 | 2227 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
class TestNSSet : XCTestCase {
var allTests : [(String, () -> Void)] {
return [
("test_BasicConstruction", test_BasicConstruction),
("test_enumeration", test_enumeration),
("test_sequenceType", test_sequenceType),
("test_setOperations", test_setOperations),
]
}
func test_BasicConstruction() {
let set = NSSet()
let set2 = NSSet(array: ["foo", "bar"].bridge().bridge())
XCTAssertEqual(set.count, 0)
XCTAssertEqual(set2.count, 2)
}
func test_enumeration() {
let set = NSSet(array: ["foo", "bar", "baz"].bridge().bridge())
let e = set.objectEnumerator()
var result = Set<String>()
result.insert((e.nextObject()! as! NSString).bridge())
result.insert((e.nextObject()! as! NSString).bridge())
result.insert((e.nextObject()! as! NSString).bridge())
XCTAssertEqual(result, Set(["foo", "bar", "baz"]))
let empty = NSSet().objectEnumerator()
XCTAssertNil(empty.nextObject())
XCTAssertNil(empty.nextObject())
}
func test_sequenceType() {
let set = NSSet(array: ["foo", "bar", "baz"].bridge().bridge())
var res = Set<String>()
for obj in set {
res.insert((obj as! NSString).bridge())
}
XCTAssertEqual(res, Set(["foo", "bar", "baz"]))
}
func test_setOperations() {
// TODO: This fails because hashValue and == use NSObject's implementaitons, which don't have the right semantics
// let set = NSMutableSet(array: ["foo", "bar"])
// set.unionSet(["bar", "baz"])
// XCTAssertTrue(set.isEqualToSet(["foo", "bar", "baz"]))
}
} | apache-2.0 | e82e859fe478a88e636d489a12cc16db | 31.289855 | 121 | 0.600808 | 4.241905 | false | true | false | false |
macrigiuseppe/swift-calculator | Calculator/ViewController.swift | 1 | 2183 | //
// ViewController.swift
// Calculator
//
// Created by Giuseppe Macri on 6/7/15.
// Copyright (c) 2015 Giuseppe Macri. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
var operandStack = Array<Double>()
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
println("operandStack = \(operandStack)")
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!;
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case "×": performOperation() { $0 * $1 } // last argument can go outside paranthesis
case "÷": performOperation { $1 / $0 } // if the last argument is the only one you can remove parenthesis at all
case "+": performOperation { $0 + $1 }
case "-": performOperation { $1 - $0 }
case "√": performOperation { sqrt($0) }
default: break
}
}
private func performOperation(operation: (Double, Double) -> Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}
private func performOperation(operation: Double -> Double) {
if operandStack.count >= 1 {
displayValue = operation(operandStack.removeLast())
enter()
}
}
}
| apache-2.0 | 28cbcf2c1a1bc6e9151489d0277c0192 | 26.582278 | 120 | 0.585131 | 5.200477 | false | false | false | false |
san2ride/NavColonialStock | ColonialStockTransfer/ColonialStockTransfer/ProxyVotingTableViewController.swift | 1 | 970 | //
// ProxyVotingTableViewController.swift
// ColonialStockTransfer
//
// Created by don't touch me on 10/31/16.
// Copyright © 2016 trvl, LLC. All rights reserved.
//
import UIKit
class ProxyVotingTableViewController: UITableViewController {
var proxy = ["Proxy Voting","How to Vote Online", "View Proxy Materials Online"]
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return proxy.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell5", for: indexPath)
let proxyName = proxy[indexPath.row]
cell.textLabel?.text = proxyName
cell.imageView?.image = UIImage(named: proxyName)
return cell
}
}
| mit | da4433ef3d0aae9b361969577fabac2b | 23.846154 | 109 | 0.673891 | 4.75 | false | false | false | false |
zakkhoyt/ColorPicKit | ColorPicKit/Classes/RGBASliderGroup.swift | 1 | 3873 | //
// RGBASliderGroup.swift
// ColorPicKitExample
//
// Created by Zakk Hoyt on 10/26/16.
// Copyright © 2016 Zakk Hoyt. All rights reserved.
//
import UIKit
@IBDesignable public class RGBASliderGroup: SliderGroup {
public override var intrinsicContentSize: CGSize {
get {
if showAlphaSlider {
let height = 3 * spacing + 4.0 * sliderHeight
return CGSize(width: bounds.width, height: height)
} else {
let height = 2 * spacing + 3.0 * sliderHeight
return CGSize(width: bounds.width, height: height)
}
}
}
fileprivate var redSlider: GradientSlider!
fileprivate var greenSlider: GradientSlider!
fileprivate var blueSlider: GradientSlider!
fileprivate var alphaSlider: GradientSlider!
override func configureSliders() {
let rgba = color.rgba()
redSlider = GradientSlider()
redSlider.color1 = UIColor.white
redSlider.color2 = UIColor.red
redSlider.value = rgba.red
addSubview(redSlider)
sliders.append(redSlider)
greenSlider = GradientSlider()
greenSlider.color1 = UIColor.white
greenSlider.color2 = UIColor.green
greenSlider.value = rgba.green
addSubview(greenSlider)
sliders.append(greenSlider)
blueSlider = GradientSlider()
blueSlider.color1 = UIColor.white
blueSlider.color2 = UIColor.blue
blueSlider.value = rgba.blue
addSubview(blueSlider)
sliders.append(blueSlider)
if showAlphaSlider {
alphaSlider = GradientSlider()
alphaSlider.color1 = UIColor.clear
alphaSlider.color2 = UIColor.white
alphaSlider.value = rgba.alpha
addSubview(alphaSlider)
sliders.append(alphaSlider)
}
}
override func colorFromSliders() -> UIColor {
guard let _ = redSlider,
let _ = greenSlider,
let _ = blueSlider,
let _ = alphaSlider else {
print("sliders not configured");
return UIColor.clear
}
let red = redSlider.value
let green = greenSlider.value
let blue = blueSlider.value
let alpha = alphaSlider.value
let rgba = RGBA(red: red, green: green, blue: blue, alpha: alpha)
return rgba.color()
}
override func slidersFrom(color: UIColor) {
let rgba = color.rgba()
redSlider.value = rgba.red
greenSlider.value = rgba.green
blueSlider.value = rgba.blue
alphaSlider.value = rgba.alpha
updateSliderColors()
}
override func updateSliderColors() {
if self.realtimeMix {
let rgba = self.color.rgba()
redSlider.color1 = UIColor(red: 0, green: rgba.green, blue: rgba.blue, alpha: rgba.alpha)
redSlider.color2 = UIColor(red: 1.0, green: rgba.green, blue: rgba.blue, alpha: rgba.alpha)
greenSlider.color1 = UIColor(red: rgba.red, green: 0, blue: rgba.blue, alpha: rgba.alpha)
greenSlider.color2 = UIColor(red: rgba.red, green: 1.0, blue: rgba.blue, alpha: rgba.alpha)
blueSlider.color1 = UIColor(red: rgba.red, green: rgba.green, blue: 0.0, alpha: rgba.alpha)
blueSlider.color2 = UIColor(red: rgba.red, green: rgba.green, blue: 1.0, alpha: rgba.alpha)
redSlider.knobView.color = self.color
greenSlider.knobView.color = self.color
blueSlider.knobView.color = self.color
alphaSlider.knobView.color = self.color
}
}
}
| mit | 149e52d580912a0d12b89d68835a5673 | 26.076923 | 103 | 0.573605 | 4.631579 | false | false | false | false |
Limon-O-O/KingfisherExtension | Example/Example/ViewController.swift | 1 | 2176 | //
// ViewController.swift
// KingfisherExtension
//
// Created by catch on 15/11/17.
// Copyright © 2015年 KingfisherExtension. All rights reserved.
//
import UIKit
import KingfisherExtension
class ViewController: UIViewController {
@IBOutlet fileprivate weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.contentInset.top = 20.0
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: nil), forCellWithReuseIdentifier: CollectionViewCell.kfe_className)
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let URLString = "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/kingfisher-\((indexPath as NSIndexPath).row + 1).jpg"
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.kfe_className, for: indexPath) as! CollectionViewCell
let squareTransformer = Transformer(URLString: URLString, style: Style.square)
let transformer1 = Transformer(URLString: URLString, style: Style.round1)
let transformer2 = Transformer(URLString: URLString, style: Style.round2)
let transformer3 = Transformer(URLString: URLString, style: Style.round3)
cell.imageView.kfe_setImage(byTransformer: squareTransformer)
cell.imageView1.kfe_setImage(byTransformer: transformer1)
cell.imageView2.kfe_setImage(byTransformer: transformer2)
cell.imageView3.kfe_setImage(byTransformer: transformer3)
cell.button.kfe_setImage(byTransformer: transformer3)
return cell
}
}
extension ViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: ScreenWidth, height: 100)
}
}
| mit | ae0db019e54551733a506e090d88573a | 34.622951 | 147 | 0.747814 | 5.077103 | false | false | false | false |
XCEssentials/UniFlow | Sources/5_MutationDecriptors/1-InitializationOf.swift | 1 | 1723 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation /// for access to `Date` type
//---
public
struct InitializationOf<F: SomeFeature>: SomeMutationDecriptor
{
public
let newState: SomeStateBase
public
let timestamp: Date
public
init?(
from report: Storage.HistoryElement
) {
guard
report.feature == F.self,
let initialization = Initialization(from: report)
else
{
return nil
}
//---
self.newState = initialization.newState
self.timestamp = report.timestamp
}
}
| mit | 84da0e6e1c168e69969e391bbe63ffb6 | 28.706897 | 79 | 0.702263 | 4.994203 | false | false | false | false |
nasser0099/Express | Express/AnyContent+JSON.swift | 1 | 1625 | //===--- AnyContent+JSON.swift --------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
import TidyJSON
public extension AnyContent {
func asJSON() -> JSON? {
for ct in contentType {
//TODO: move to constants
if "application/json" == ct {
do {
guard let text = self.asText() else {
return nil
}
let json = try JSON.parse(text)
return json
} catch let e as TidyJSON.ParseError {
print(e)
return nil
} catch let e {
print(e)
return nil
}
}
}
return nil
}
} | gpl-3.0 | d6188823263eaed3cc8e921caa3f3694 | 33.595745 | 80 | 0.531692 | 5.062305 | false | false | false | false |
objecthub/swift-lispkit | Sources/LispKit/Base/ScanBuffer.swift | 1 | 2257 | //
// ScanBuffer.swift
// LispKit
//
// Created by Matthias Zenger on 07/06/2016.
// Copyright © 2016 ObjectHub. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
///
/// Data structure for accumulating characters in a buffer.
///
public struct ScanBuffer {
private var buffer: ContiguousArray<UniChar>
public private(set) var index: Int
public init(capacity: Int = 256) {
self.buffer = ContiguousArray<UniChar>(repeating: 0, count: capacity)
self.index = 0
}
public mutating func reset() {
if self.index > 0 {
self.buffer[0] = self.buffer[self.index - 1]
self.index = 1
}
}
public mutating func append(_ ch: UniChar) {
if self.index < self.buffer.count {
self.buffer[self.index] = ch
} else {
self.buffer.append(ch)
}
self.index += 1
}
public var stringValue: String {
return self.index > 0 ? self.buffer.withUnsafeBufferPointer { ptr in
if let adr = ptr.baseAddress {
return String(utf16CodeUnits: adr, count: self.index - 1)
} else {
return ""
}
}
: ""
}
public func stringStartingAt(_ start: Int) -> String {
guard self.index > start else {
return ""
}
guard start > 0 else {
return self.stringValue
}
let temp = self.buffer[start..<self.index - 1]
return temp.withUnsafeBufferPointer { ptr in
if let adr = ptr.baseAddress {
return String(utf16CodeUnits: adr, count: temp.count)
} else {
return ""
}
}
}
}
| apache-2.0 | a11dacfa5afed888bd51ec7b21b1288e | 27.923077 | 89 | 0.595301 | 4.193309 | false | false | false | false |
MR-Zong/ZGResource | Project/FamilyEducationApp-master/家教/RealName ViewController.swift | 1 | 3751 | //
// FreeTimeTableViewController.swift
// 家教
//
// Created by goofygao on 15/10/21.
// Copyright © 2015年 goofyy. All rights reserved.
//
import UIKit
class RealNameViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate {
@IBOutlet weak var personalIDcard: UITextField!
@IBOutlet weak var getIDcardBackPicture: UIButton!
@IBOutlet weak var getIDcardfrontPicture: UIButton!
@IBOutlet weak var uploadButton: UIButton!
var alertView = CustomAlertView()
var buttonIdentify = 0
var IDcardFontImage:UIImage?
var IDcardBackImage:UIImage?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "实名认证"
let navBar = self.navigationController?.navigationBar
navBar?.barTintColor = UIColor(red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1)
navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
getIDcardBackPicture.layer.cornerRadius = 5
getIDcardBackPicture.layer.masksToBounds = true
getIDcardfrontPicture.layer.cornerRadius = 5
getIDcardfrontPicture.layer.masksToBounds = true
personalIDcard.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func getIDcardPictureAction(sender: UIButton) {
buttonIdentify = sender.tag
if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){
//初始化图片控制器
let picker = UIImagePickerController()
//设置代理
picker.delegate = self
//指定图片控制器类型
picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
//弹出控制器,显示界面
self.presentViewController(picker, animated: true, completion: {
() -> Void in
})
}else{
print("读取相册错误")
}
}
@IBAction func uploadAction(sender: UIButton) {
if IDcardFontImage == nil || IDcardBackImage == nil {
let alertViewEWarning = UIAlertView(title: "提示", message: "上传前请把图片填充完整", delegate: nil, cancelButtonTitle: "返回")
alertViewEWarning.show()
}
}
//选择图片成功后代理
func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print(buttonIdentify)
//查看info对象
print(info["UIImagePickerControllerReferenceURL"])
print(info)
//获取选择的原图
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
if buttonIdentify == 50 {
IDcardFontImage = image
getIDcardfrontPicture.setImage(image, forState: UIControlState.Normal)
} else {
IDcardBackImage = image
getIDcardBackPicture.setImage(image, forState: UIControlState.Normal)
}
//图片控制器退出
picker.dismissViewControllerAnimated(true, completion: {
() -> Void in
})
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.personalIDcard.resignFirstResponder()
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.personalIDcard.resignFirstResponder()
return true
}
}
| gpl-2.0 | d520b9acf6463169999d18a1f51ab1a4 | 31.825688 | 132 | 0.63611 | 5.185507 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/ToneAnalyzerV3/Models/SentenceAnalysis.swift | 1 | 2293 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** SentenceAnalysis. */
public struct SentenceAnalysis: Decodable {
/// The unique identifier of a sentence of the input content. The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one.
public var sentenceID: Int
/// The text of the input sentence.
public var text: String
/// **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned.
public var tones: [ToneScore]?
/// **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the `tones` parameter of the request.
public var toneCategories: [ToneCategory]?
/// **`2017-09-21`:** Not returned. **`2016-05-19`:** The offset of the first character of the sentence in the overall input content.
public var inputFrom: Int?
/// **`2017-09-21`:** Not returned. **`2016-05-19`:** The offset of the last character of the sentence in the overall input content.
public var inputTo: Int?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case sentenceID = "sentence_id"
case text = "text"
case tones = "tones"
case toneCategories = "tone_categories"
case inputFrom = "input_from"
case inputTo = "input_to"
}
}
| mit | 46d86f6a719d7e752ee471d57530f41a | 44.86 | 311 | 0.704317 | 4.169091 | false | false | false | false |
yoshinorisano/RxSwift | RxExample/RxExample/Examples/WikipediaImageSearch/ViewModels/SearchViewModel.swift | 13 | 1465 | //
// SearchViewModel.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
class SearchViewModel {
// outputs
let rows: Observable<[SearchResultViewModel]>
let subscriptions = DisposeBag()
// public methods
init(searchText: Observable<String>,
selectedResult: Observable<SearchResultViewModel>) {
let $: Dependencies = Dependencies.sharedDependencies
let wireframe = Dependencies.sharedDependencies.wireframe
let API = DefaultWikipediaAPI.sharedAPI
self.rows = searchText
.throttle(0.3, $.mainScheduler)
.distinctUntilChanged()
.map { query in
API.getSearchResults(query)
.retry(3)
.startWith([]) // clears results on new search term
.catchErrorJustReturn([])
}
.switchLatest()
.map { results in
results.map {
SearchResultViewModel(
searchResult: $0
)
}
}
selectedResult
.subscribeNext { searchResult in
wireframe.openURL(searchResult.searchResult.URL)
}
.addDisposableTo(subscriptions)
}
} | mit | aeaba2b49e64f3a567ea99c8e208bb7c | 25.178571 | 71 | 0.551536 | 5.678295 | false | false | false | false |
kentaiwami/masamon | masamon/masamon/ShiftImportSetting.swift | 1 | 4360 | //
// ShiftImportSetting.swift
// masamon
//
// Created by 岩見建汰 on 2016/05/08.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
import Eureka
class ShiftImportSetting: FormViewController {
var default_staff_name = ""
var default_staff_count = 0
override func viewDidLoad() {
super.viewDidLoad()
CreateForm()
}
func CreateForm() {
let RuleRequired_M = "必須項目です"
LabelRow.defaultCellUpdate = { cell, row in
cell.contentView.backgroundColor = .red
cell.textLabel?.textColor = .white
cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 13)
cell.textLabel?.textAlignment = .right
}
default_staff_name = ""
default_staff_count = 0
if DBmethod().DBRecordCount(UserNameDB.self) != 0 {
default_staff_name = DBmethod().UserNameGet()
default_staff_count = DBmethod().StaffNumberGet()
}
form +++ Section("")
<<< TextRow() {
$0.title = "シフト表での名前"
$0.value = default_staff_name
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
$0.tag = "name"
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
<<< IntRow(){
$0.title = "従業員の人数"
$0.value = default_staff_count
$0.tag = "count"
$0.add(rule: RuleRequired())
$0.validationOptions = .validatesOnChange
}
.onRowValidationChanged { cell, row in
let rowIndex = row.indexPath!.row
while row.section!.count > rowIndex + 1 && row.section?[rowIndex + 1] is LabelRow {
row.section?.remove(at: rowIndex + 1)
}
if !row.isValid {
for (index, _) in row.validationErrors.map({ $0.msg }).enumerated() {
let labelRow = LabelRow() {
$0.title = RuleRequired_M
$0.cell.height = { 30 }
}
row.section?.insert(labelRow, at: row.indexPath!.row + index + 1)
}
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
var validate_err_count = 0
for row in form.allRows {
validate_err_count += row.validate().count
}
if validate_err_count == 0 {
let name = form.values()["name"] as! String
let count = form.values()["count"] as! Int
let staffnumberrecord = StaffNumberDB()
staffnumberrecord.id = 0
staffnumberrecord.number = count
let usernamerecord = UserNameDB()
usernamerecord.id = 0
usernamerecord.name = name
DBmethod().AddandUpdate(usernamerecord, update: true)
DBmethod().AddandUpdate(staffnumberrecord, update: true)
}else {
present(Utility().GetStandardAlert(title: "エラー", message: "入力されていない項目があるため保存できませんでした", b_title: "OK"),animated: false, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 34c72e590de13c14fa4711fa24672d80 | 35.042373 | 147 | 0.479426 | 4.757271 | false | false | false | false |
kentaiwami/masamon | masamon/masamon/OriginUITabBarController.swift | 1 | 1118 | //
// OriginUITabBarController.swift
// masamon
//
// Created by 岩見建汰 on 2016/04/30.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
class OriginUITabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
self.tabBar.barTintColor = UIColor.hex("191919", alpha: 1.0)
self.tabBar.isTranslucent = false
let fontFamily: UIFont! = UIFont.systemFont(ofSize: 10)
let selectedColor:UIColor = UIColor.hex("FF8E92", alpha: 1.0)
// let selectedAttributes = NSAttributedStringKey.font.rawValue: fontFamily, NSAttributedStringKey.foregroundColor: selectedColor
let selectedAttributes = [NSAttributedStringKey.font: fontFamily, NSAttributedStringKey.foregroundColor: selectedColor] as [NSAttributedStringKey : Any]
self.tabBarItem.setTitleTextAttributes(selectedAttributes, for: UIControlState.selected)
UITabBar.appearance().tintColor = selectedColor
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 7474f2129804a1be28d906f216904f10 | 31.558824 | 160 | 0.704607 | 4.941964 | false | false | false | false |
luckymore0520/leetcode | ReverseNodesInK-Group.playground/Contents.swift | 1 | 2482 | //: Playground - noun: a place where people can play
import UIKit
//
//Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
//
//k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
//
//You may not alter the values in the nodes, only nodes itself may be changed.
//
//Only constant memory is allowed.
//
//For example,
//Given this linked list: 1->2->3->4->5
//
//For k = 2, you should return: 2->1->4->3->5
//
//For k = 3, you should return: 3->2->1->4->5
//
//Subscribe to see which companies asked this question.
extension ListNode: CustomStringConvertible {
public var toString: String {
var desc = "\(val)"
var next = self.next
while next != nil {
desc += "->\(next!.val)"
next = next!.next
}
return desc
}
public var description: String {
var desc = "\(val)"
// var next = self.next
// while next != nil {
// desc += "->\(next!.val)"
// next = next!.next
// }
return desc
}
}
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
}
class Solution {
func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
if (k <= 1) {
return head
}
guard let next = head?.next else {
return head
}
//考虑剩下的如果小于k 则不用翻转
var testNext: ListNode? = next
for _ in 1...k-1 {
if (testNext == nil ) {
return head
}
testNext = testNext?.next
}
var last = head
var current : ListNode? = next
for _ in 1...k-1 {
let tmp = current?.next;
current?.next = last
last = current
current = tmp;
if (current == nil) {
break;
}
}
head?.next = reverseKGroup(current, k)
return last
}
}
let solution = Solution()
let node1 = ListNode(1)
let node2 = ListNode(2)
let node3 = ListNode(3)
let node4 = ListNode(4)
let node5 = ListNode(5)
node4.next = node5
node3.next = node4
node2.next = node3
node1.next = node2
solution.reverseKGroup(node1, 3)?.toString | mit | 57dcbf89258ec3387228dc425df6faa5 | 24.05102 | 186 | 0.546047 | 3.816485 | false | false | false | false |
Flinesoft/BartyCrouch | Sources/BartyCrouchConfiguration/Options/UpdateOptions/TransformOptions.swift | 1 | 2456 | import BartyCrouchUtility
import Foundation
import MungoHealer
import Toml
public struct TransformOptions {
public let codePaths: [String]
public let subpathsToIgnore: [String]
public let localizablePaths: [String]
public let transformer: Transformer
public let supportedLanguageEnumPath: String
public let typeName: String
public let translateMethodName: String
public let customLocalizableName: String?
}
extension TransformOptions: TomlCodable {
static func make(toml: Toml) throws -> TransformOptions {
let update: String = "update"
let transform: String = "transform"
guard
let transformer = Transformer(
rawValue: toml.string(update, transform, "transformer") ?? Transformer.foundation.rawValue
)
else {
throw MungoError(
source: .invalidUserInput,
message: "Unknown `transformer` provided in [update.code.transform]. Supported: \(Transformer.allCases)"
)
}
return TransformOptions(
codePaths: toml.filePaths(update, transform, singularKey: "codePath", pluralKey: "codePaths"),
subpathsToIgnore: toml.array(update, transform, "subpathsToIgnore") ?? Constants.defaultSubpathsToIgnore,
localizablePaths: toml.filePaths(
update,
transform,
singularKey: "localizablePath",
pluralKey: "localizablePaths"
),
transformer: transformer,
supportedLanguageEnumPath: toml.string(update, transform, "supportedLanguageEnumPath") ?? ".",
typeName: toml.string(update, transform, "typeName") ?? "BartyCrouch",
translateMethodName: toml.string(update, transform, "translateMethodName") ?? "translate",
customLocalizableName: toml.string(update, transform, "customLocalizableName")
)
}
func tomlContents() -> String {
var lines: [String] = ["[update.transform]"]
lines.append("codePaths = \(codePaths)")
lines.append("subpathsToIgnore = \(subpathsToIgnore)")
lines.append("localizablePaths = \(localizablePaths)")
lines.append("transformer = \"\(transformer.rawValue)\"")
lines.append("supportedLanguageEnumPath = \"\(supportedLanguageEnumPath)\"")
lines.append("typeName = \"\(typeName)\"")
lines.append("translateMethodName = \"\(translateMethodName)\"")
if let customLocalizableName = customLocalizableName {
lines.append("customLocalizableName = \"\(customLocalizableName)\"")
}
return lines.joined(separator: "\n")
}
}
| mit | 6f47b0eb381d3ada3e826fdc0cb98a3f | 35.656716 | 112 | 0.707248 | 4.548148 | false | false | false | false |
Deliany/yaroslav_skorokhid_SimplePins | yaroslav_skorokhid_SimplePins/OAuthSocial.swift | 1 | 3657 | //
// OAuthSocial.swift
// yaroslav_skorokhid_SimplePins
//
// Created by Yaroslav Skorokhid on 10/15/16.
// Copyright © 2016 CollateralBeauty. All rights reserved.
//
import Foundation
class OAuthSocial {
var baseURL: String
var authPath: String
var clientID: String
var clientSecret: String?
var responseType: String
var redirectURI: NSURL
var scope: String?
private let OAuthControllerAccessTokenKey = "access_token"
private let OAuthControllerErrorKey = "error"
private let OAuthControllerAccessDeniedKey = "access_denied"
private let OAuthControllerCodeKey = "code"
var authorizeHandler: (() -> Void)?
var authorizeCompletionClosure: ((credentials: OAuthCredentials?, errorString: String?) -> Void)?
init(baseURL: String, authPath: String, clientID: String, clientSecret: String?, responseType: String, redirectURI: NSURL, scope: String?) {
self.baseURL = baseURL
self.authPath = authPath
self.clientID = clientID
self.responseType = responseType
self.redirectURI = redirectURI
self.scope = scope
}
func authorize() {
self.authorizeHandler?()
}
func handleRedirectURL(url: NSURL) {
let response = OAuthResponseParser.parseURL(url)
self.processResponse(response)
}
private func processResponse(response: [String: AnyObject]) {
if let error = response[OAuthControllerErrorKey] as? String {
self.authorizeCompletionClosure?(credentials: nil, errorString: error)
}
else if let _ = response[OAuthControllerAccessTokenKey] as? String {
self.authorizeCompletionClosure?(credentials: OAuthManager.credentialsByResponse(response), errorString: nil)
}
else if let accessCode = response[OAuthControllerCodeKey] as? String {
self.authorizeWithAccessCode(accessCode)
}
else {
self.authorizeCompletionClosure?(credentials: nil, errorString: NSLocalizedString("Error while processing response", comment: ""))
}
}
private func authorizeWithAccessCode(accessCode: String) {
OAuthManager.authenticateWithSocialOAuth(self, code: accessCode) { [weak self] (response, errorString) in
if let response = response {
self?.processResponse(response)
}
else if let error = errorString {
self?.authorizeCompletionClosure?(credentials: nil, errorString: error)
}
}
}
func OAuthURL() -> NSURL {
var stringURL = self.defaultOAuthStringURL()
stringURL += "&response_type=\(self.responseType)"
if let scope = self.scope {
stringURL += "&scope=\(scope)"
}
let additionalParameters = self.OAuthURLAdditionalParameters()
for (key, value) in additionalParameters {
stringURL += "&\(key)=\(value)"
}
stringURL += "&grant_type=password"
let OAuthURL = NSURL(string: stringURL)!
return OAuthURL
}
func OAuthAccessTokenByCode(code: String) -> NSURL {
var stringURL = self.defaultOAuthStringURL()
stringURL += "&code=\(code)&clientSecret=\(self.clientSecret)&grant_type=authorization_code"
let OAuthURL = NSURL(string: stringURL)!
return OAuthURL
}
func OAuthURLAdditionalParameters() -> [String: AnyObject] {
return [:]
}
private func defaultOAuthStringURL() -> String {
return "\(self.baseURL)\(self.authPath)?client_id=\(self.clientID)&redirect_uri=\(self.redirectURI)"
}
} | mit | ec69c64a6e66e3b8cddaec042de0d955 | 35.207921 | 144 | 0.647429 | 4.842384 | false | false | false | false |
wwq0327/iOS8Example | Diary/Diary/DiaryLocationHelper.swift | 1 | 2973 | //
// DiaryLocationHelper.swift
// Diary
//
// Created by wyatt on 15/6/14.
// Copyright (c) 2015年 Wanqing Wang. All rights reserved.
//
import CoreLocation
class DiaryLocationHelper: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var currentLocation: CLLocation?
var address: String?
var geocoder = CLGeocoder()
override init() {
super.init()
locationManager.delegate = self
// 位置更新的位移触发条件
locationManager.distanceFilter = kCLDistanceFilterNone
// 精度
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// 如果用户停止移动则停止更新位置
locationManager.pausesLocationUpdatesAutomatically = true
// 指南针触发条件
locationManager.headingFilter = kCLHeadingFilterNone
// 请求位置权限
locationManager.requestWhenInUseAuthorization()
println("Location Right")
// 判断是否有位置权限
if (CLLocationManager.locationServicesEnabled()) {
// 开始更新位置
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var locationInfo = locations.last as! CLLocation
// println(locationInfo)
geocoder.reverseGeocodeLocation(locationInfo, completionHandler: { (placemarks, error) -> Void in
if (error != nil) {
println("reverse geodcode fail: \(error.localizedDescription)")
}
if let pm = placemarks.first as? CLPlacemark {
self.address = pm.name
NSNotificationCenter.defaultCenter().postNotificationName("DiaryLocationUpdated", object: self.address)
}
})
}
// 失败则停止定位
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println(error)
locationManager.stopUpdatingLocation()
}
// func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
// // 位置更新后通过CLGeocoder获取位置描述, 例如广州市
// geocoder.reverseGeocodeLocation(newLocation, completionHandler: { (placemarks, error) -> Void in
// if (error != nil) {
// println("reverse geodcode fail: \(error.localizedDescription)")
// }
// if let pm = placemarks as? [CLPlacemark] {
// if pm.count > 0 {
// var placemark = pm.first
// self.address = placemark?.locality
// NSNotificationCenter.defaultCenter().postNotificationName("DiaryLocationUpdated", object: self.address)
// }
// }
// })
// }
} | apache-2.0 | a318d6e8ed9ad8044e62459fe9192466 | 35 | 142 | 0.623798 | 5.316288 | false | false | false | false |
r-mckay/montreal-iqa | montrealIqa/Carthage/Checkouts/Reusable/Example/ReusableDemo iOS/TableViewController.swift | 1 | 2557 | //
// ViewController.swift
// ReusableDemo
//
// Created by Olivier Halligon on 19/01/2016.
// Copyright © 2016 AliSoftware. All rights reserved.
//
import UIKit
final class TableViewController: UITableViewController {
var boolValues = [false, false]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(cellType: MySimpleColorCell.self)
tableView.register(cellType: MyXIBTextCell.self)
tableView.register(cellType: MyXIBInfoCell.self)
/* No need to register this one, the UIStoryboard already auto-register its cells */
// tableView.registerReusableCell(MyStoryBoardIndexPathCell)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return MyHeaderTableView.height
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let frame = CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: self.tableView(tableView, heightForHeaderInSection: section))
// See the overridden `MyHeaderTableView.init(frame:)` initializer, which
// automatically loads the view content from its nib using loadNibContent()
let view = MyHeaderTableView(frame: frame)
view.fillForSection(section)
return view
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let colorCell = tableView.dequeueReusableCell(for: indexPath) as MySimpleColorCell
let red: CGFloat = indexPath.row == 0 ? 1.0 : 0.0
colorCell.fill(UIColor(red: red, green: 0.0, blue: 1-red, alpha: 1.0))
return colorCell
case 1:
let textCell = tableView.dequeueReusableCell(for: indexPath) as MyXIBTextCell
textCell.fill("{section \(indexPath.section), row \(indexPath.row)}")
return textCell
case 2:
let infoCell = tableView.dequeueReusableCell(for: indexPath) as MyXIBInfoCell
infoCell.fill("InfoCell #\(indexPath.row)", info: "Info #\(indexPath.row)", details: "Details #\(indexPath.row)")
return infoCell
case 3:
let pathCell = tableView.dequeueReusableCell(for: indexPath) as MyStoryBoardIndexPathCell
pathCell.fill(indexPath)
return pathCell
default:
fatalError("Out of bounds, should not happen")
}
}
}
| mit | e72e085d525b0f9231e2b7a9e81ca304 | 35.514286 | 140 | 0.719875 | 4.399312 | false | false | false | false |
akaimo/LNFloatingActionButton | LNFloatingActionButton-Example/LNFloatingActionButton-Example/TitleCellViewController.swift | 1 | 2226 | //
// TitleCellViewController.swift
// LNFloatingActionButton-Example
//
// Created by Shuhei Kawaguchi on 2017/10/02.
// Copyright © 2017年 Shuhei Kawaguchi. All rights reserved.
//
import UIKit
import LNFloatingActionButton
class TitleCellViewController: UIViewController {
var cells: [LNFloatingActionButtonCell] = []
override func viewDidLoad() {
super.viewDidLoad()
let cell: LNFloatingActionButtonTitleCell = {
let cell = LNFloatingActionButtonTitleCell()
cell.title = "like button"
cell.image = UIImage(named: "like")
return cell
}()
cells.append(cell)
let cell2: LNFloatingActionButtonTitleCell = {
let cell = LNFloatingActionButtonTitleCell()
cell.title = "home button"
cell.image = UIImage(named: "home")
return cell
}()
cells.append(cell2)
let fab: LNFloatingActionButton = {
let fab = LNFloatingActionButton(x: view.frame.size.width - 100, y: view.frame.size.height - 100)
fab.dataSource = self
fab.delegate = self
fab.color = .white
fab.shadowOffset = CGSize(width: 0.0, height: 2.0)
fab.shadowOpacity = 0.5
fab.shadowRadius = 2.0
fab.shadowPath = fab.circlePath
fab.closedImage = UIImage(named: "plus")
fab.cellMargin = 10
return fab
}()
view.addSubview(fab)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension TitleCellViewController: LNFloatingActionButtonDelegate {
func floatingActionButton(_ floatingActionButton: LNFloatingActionButton, didSelectItemAtIndex index: Int) {
print(index)
floatingActionButton.close()
}
}
extension TitleCellViewController: LNFloatingActionButtonDataSource {
func numberOfCells(_ floatingActionButton: LNFloatingActionButton) -> Int {
return cells.count
}
func cellForIndex(_ index: Int) -> LNFloatingActionButtonCell {
return cells[index]
}
}
| mit | fc02b9179d9c8d30eecfa1f2bee369e8 | 28.64 | 112 | 0.62978 | 4.864333 | false | false | false | false |
faraxnak/PayWandBasicElements | Pods/EasyPeasy/EasyPeasy/PositionAttribute+UIKit.swift | 4 | 10813 | // The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
/**
PositionAttribute extension adding some convenience methods to operate with
UIKit elements as `UIViews` or `UILayoutGuides`
*/
public extension PositionAttribute {
/**
Establishes a position relationship between the `UIView` the attribute
is applied to and the `UIView` passed as parameter.
It's also possible to link this relationship to a particular attribute
of the `view` parameter by supplying `attribute`.
- parameter view: The reference view
- parameter attribute: The attribute of `view` we are establishing the
relationship to
- returns: The current `Attribute` instance
*/
@discardableResult public func to(_ view: UIView, _ attribute: ReferenceAttribute? = nil) -> Self {
self.referenceItem = view
self.referenceAttribute = attribute
return self
}
/**
Establishes a position relationship between the `UIView` the attribute
is applied to and the `UILayoutSupport` passed as parameter.
It's also possible to link this relationship to a particular attribute
of the `layoutSupport` parameter by supplying `attribute`.
- parameter layoutSupport: The reference `UILayoutSupport`
- parameter attribute: The attribute of `view` we are establishing the
relationship to
- returns: The current `Attribute` instance
*/
@discardableResult public func to(_ layoutSupport: UILayoutSupport, _ attribute: ReferenceAttribute? = nil) -> Self {
self.referenceItem = layoutSupport
self.referenceAttribute = attribute
return self
}
/**
Establishes a position relationship between the `UIView` the attribute
is applied to and the `UILayoutGuide` passed as parameter.
It's also possible to link this relationship to a particular attribute
of the `view` parameter by supplying `attribute`.
- parameter layoutGuide: The reference `UILayoutGuide`
- parameter attribute: The attribute of `view` we are establishing the
relationship to
- returns: The current `Attribute` instance
*/
@available(iOS 9.0, *)
@discardableResult public func to(_ layoutGuide: UILayoutGuide, _ attribute: ReferenceAttribute? = nil) -> Self {
self.referenceItem = layoutGuide
self.referenceAttribute = attribute
return self
}
}
/**
The object’s left margin. For UIView objects, the margins are defined
by their layoutMargins property
*/
public class LeftMargin: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .leftMargin
}
}
/**
The object’s right margin. For UIView objects, the margins are defined
by their layoutMargins property
*/
public class RightMargin: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .rightMargin
}
}
/**
The object’s top margin. For UIView objects, the margins are defined
by their layoutMargins property
*/
public class TopMargin: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .topMargin
}
}
/**
The object’s bottom margin. For UIView objects, the margins are defined
by their layoutMargins property
*/
public class BottomMargin: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .bottomMargin
}
}
/**
The object’s leading margin. For UIView objects, the margins are defined
by their layoutMargins property
*/
public class LeadingMargin: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .leadingMargin
}
}
/**
The object’s trailing margin. For UIView objects, the margins are defined
by their layoutMargins property
*/
public class TrailingMargin: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .trailingMargin
}
}
/**
The center along the x-axis between the object’s left and right margin.
For UIView objects, the margins are defined by their layoutMargins property
*/
public class CenterXWithinMargins: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .centerXWithinMargins
}
}
/**
The center along the y-axis between the object’s top and bottom margin.
For UIView objects, the margins are defined by their layoutMargins property
*/
public class CenterYWithinMargins: PositionAttribute {
/// `Attribute` applied to the view
public override var createAttribute: ReferenceAttribute {
return .centerYWithinMargins
}
}
/**
The object’s margins. For UIView objects, the margins are defined
by their layoutMargins property
*/
public class Margins: CompoundAttribute {
/**
Initializer that creates the sub `Attribute` objects
shaping the `CompoundAttribute` object with `constant = 0.0`,
`multiplier = 1.0` and `RelatedBy = .Equal`
- returns: the `CompoundAttribute` instance created
*/
public override init() {
super.init()
self.attributes = [
TopMargin(),
LeftMargin(),
RightMargin(),
BottomMargin()
]
}
/**
Initializer that creates the sub `Attribute` objects shaping the
`CompoundAttribute` object with `constant = value`, `multiplier = 1.0`
and `RelatedBy = .Equal`
- parameter value: `constant` of the constraint
- returns: the `CompoundAttribute` instance created
*/
public override init(_ value: CGFloat) {
super.init()
self.attributes = [
TopMargin(value),
LeftMargin(value),
RightMargin(value),
BottomMargin(value)
]
}
/**
Initializer that creates the sub `Attribute` objects shaping the
`CompoundAttribute` object with `constant`, `multiplier` and
`RelatedBy` properties defined by the `Constant` supplied
- parameter constant: `Constant` struct aggregating
`constant`, `multiplier` and `relatedBy` properties
- returns: the `CompoundAttribute` instance created
*/
public override init(_ constant: Constant) {
super.init()
self.attributes = [
TopMargin(constant),
LeftMargin(constant),
RightMargin(constant),
BottomMargin(constant)
]
}
/**
Initializer that creates the sub `Attribute` objects shaping the
`CompoundAttribute` object with the `constant` properties specified by
the `UIEdgeInsets` parameter, `multiplier = 1.0` and `RelatedBy = .Equal`
- parameter edgeInsets: `UIEdgeInsets` that gives value to the `constant`
properties of each one of the sub `Attribute` objects
- returns: the `CompoundAttribute` instance created
*/
public init(_ edgeInsets: EdgeInsets) {
super.init()
self.attributes = [
TopMargin(CGFloat(edgeInsets.top)),
LeftMargin(CGFloat(edgeInsets.left)),
RightMargin(CGFloat(edgeInsets.right)),
BottomMargin(CGFloat(edgeInsets.bottom))
]
}
}
/**
The center along the x-axis between the object’s left and right margin.
For UIView objects, the margins are defined by their layoutMargins property
*/
public class CenterWithinMargins: CompoundAttribute {
/**
Initializer that creates the sub `Attribute` objects
shaping the `CompoundAttribute` object with `constant = 0.0`,
`multiplier = 1.0` and `RelatedBy = .Equal`
- returns: the `CompoundAttribute` instance created
*/
public override init() {
super.init()
self.attributes = [
CenterXWithinMargins(),
CenterYWithinMargins()
]
}
/**
Initializer that creates the sub `Attribute` objects shaping the
`CompoundAttribute` object with `constant = value`, `multiplier = 1.0`
and `RelatedBy = .Equal`
- parameter value: `constant` of the constraint
- returns: the `CompoundAttribute` instance created
*/
public override init(_ value: CGFloat) {
super.init()
self.attributes = [
CenterXWithinMargins(value),
CenterYWithinMargins(value)
]
}
/**
Initializer that creates the sub `Attribute` objects shaping the
`CompoundAttribute` object with `constant`, `multiplier` and
`RelatedBy` properties defined by the `Constant` supplied
- parameter constant: `Constant` struct aggregating
`constant`, `multiplier` and `relatedBy` properties
- returns: the `CompoundAttribute` instance created
*/
public override init(_ constant: Constant) {
super.init()
self.attributes = [
CenterXWithinMargins(constant),
CenterYWithinMargins(constant)
]
}
/**
Initializer that creates the sub `Attribute` objects shaping the
`CompoundAttribute` object with the `constant` properties specified by
the `CGPoint` parameter, `multiplier = 1.0` and `RelatedBy = .Equal`
- parameter point: `CGPoint` that gives value to the `constant`
properties of each one of the sub `Attribute` objects
- returns: the `CompoundAttribute` instance created
*/
public init(_ point: CGPoint) {
super.init()
self.attributes = [
CenterXWithinMargins(CGFloat(point.x)),
CenterYWithinMargins(CGFloat(point.y))
]
}
}
#endif
| mit | 44576f2504b0f00636990cd136a01906 | 31.905488 | 121 | 0.650514 | 5.262311 | false | false | false | false |
grpc/grpc-swift | Tests/GRPCTests/DelegatingErrorHandlerTests.swift | 1 | 1791 | /*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if canImport(NIOSSL)
import Foundation
@testable import GRPC
import Logging
import NIOCore
import NIOEmbedded
import NIOSSL
import XCTest
class DelegatingErrorHandlerTests: GRPCTestCase {
final class ErrorRecorder: ClientErrorDelegate {
var errors: [Error] = []
init() {}
func didCatchError(_ error: Error, logger: Logger, file: StaticString, line: Int) {
self.errors.append(error)
}
}
func testUncleanShutdownIsIgnored() throws {
let delegate = ErrorRecorder()
let channel =
EmbeddedChannel(handler: DelegatingErrorHandler(logger: self.logger, delegate: delegate))
channel.pipeline.fireErrorCaught(NIOSSLError.uncleanShutdown)
channel.pipeline.fireErrorCaught(NIOSSLError.writeDuringTLSShutdown)
XCTAssertEqual(delegate.errors.count, 1)
XCTAssertEqual(delegate.errors[0] as? NIOSSLError, .writeDuringTLSShutdown)
}
}
#endif // canImport(NIOSSL)
#if canImport(NIOSSL) && compiler(>=5.6)
// Unchecked because the error recorder is only ever used in the context of an EmbeddedChannel.
extension DelegatingErrorHandlerTests.ErrorRecorder: @unchecked Sendable {}
#endif // canImport(NIOSSL) && compiler(>=5.6)
| apache-2.0 | 3c2a519fbc14e8e6b264080ed2d5dd33 | 33.442308 | 95 | 0.752094 | 4.274463 | false | true | false | false |
smud/TextUserInterface | Sources/TextUserInterface/Commands/AdminCommands.swift | 1 | 8697 | //
// AdminCommands.swift
//
// This source file is part of the SMUD open source project
//
// Copyright (c) 2016 SMUD project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SMUD project authors
//
import Foundation
import Smud
class AdminCommands {
func register(with router: CommandRouter) {
router["area list"] = areaList
router["area build"] = areaBuild
router["area edit"] = areaEdit
router["area save"] = areaSave
router["area"] = area
router["room list"] = roomList
router["room info"] = roomInfo
router["room"] = room
router["dig north"] = { return self.dig(.north, $0) }
router["dig east"] = { return self.dig(.east, $0) }
router["dig south"] = { return self.dig(.south, $0) }
router["dig west"] = { return self.dig(.west, $0) }
router["dig up"] = { return self.dig(.up, $0) }
router["dig down"] = { return self.dig(.down, $0) }
router["dig"] = dig
}
func areaList(context: CommandContext) -> CommandAction {
context.send("List of areas:")
let areas = context.world.areasById.sorted { lhs, rhs in
lhs.value.title.caseInsensitiveCompare(rhs.value.title) == .orderedAscending }
let areaList = areas.map { v in " #\(v.value.id) \(v.value.title)" }.joined(separator: "\n")
context.send(areaList.isEmpty ? " none." : areaList)
return .accept
}
func areaBuild(context: CommandContext) -> CommandAction {
guard let player = context.creature as? Player else { return .next }
guard let currentRoom = context.creature.room else {
context.send("You are not standing in any area.")
return .accept
}
let newInstance = currentRoom.areaInstance.area.createInstance(mode: .forEditing)
newInstance.buildMap()
let room: Room
if let previousRoom = newInstance.roomsById[currentRoom.id] {
room = previousRoom
} else {
context.send("Can't find your current room in newly created instance. Probably it has been removed. Relocating to area's default room")
guard let defaultRoom = newInstance.roomsById.values.first else {
context.send("Area \(newInstance.area.id) is empty")
newInstance.area.removeInstance(newInstance)
return .accept
}
room = defaultRoom
}
player.room = room
player.editedInstances.insert(newInstance)
context.send("Relocated to \(Link(room: room)) (editing mode).")
context.creature.look()
return .accept
}
func areaEdit(context: CommandContext) -> CommandAction {
guard let player = context.creature as? Player else { return .next }
guard let room = player.room else {
context.send("You are not standing in any area.")
return .accept
}
let instance = room.areaInstance
guard !player.editedInstances.contains(instance) else {
context.send("Already editing #\(instance.area.id):\(instance.index).")
return .accept
}
player.editedInstances.insert(instance)
context.send("Enabled editing on #\(instance.area.id):\(instance.index).")
context.creature.look()
return .accept
}
func areaSave(context: CommandContext) -> CommandAction {
guard let area = context.area else {
context.send("You aren't standing in any area.")
return .accept
}
area.scheduleForSaving()
context.send("Area #\(area.id) scheduled for saving.")
return .accept
}
func area(context: CommandContext) -> CommandAction {
var result = ""
if let subcommand = context.args.scanWord() {
result += "Unknown subcommand: \(subcommand)\n"
}
result += "Available subcommands: delete, list, new, rename"
return .showUsage(result)
}
func roomList(context: CommandContext) throws -> CommandAction {
guard let areaInstance = context.scanAreaInstance(optional: true) else { return .accept }
context.send("List of #\(areaInstance.area.id):\(areaInstance.index) rooms:")
let rooms = areaInstance.roomsById.values
.sorted { $0.id < $1.id }
.map { return " #\($0.id) \($0.title)" }
.joined(separator: "\n")
context.send(rooms.isEmpty ? " none." : rooms)
return .accept
}
func roomInfo(context: CommandContext) -> CommandAction {
let room: Room
if let link = context.args.scanLink() {
guard let resolvedRoom = context.world.resolveRoom(link: link, defaultInstance: context.creature.room?.areaInstance) else {
context.send("Cant find room \(link)")
return .accept
}
room = resolvedRoom
} else {
guard let currentRoom = context.creature.room else {
context.send("You are not standing in any room.")
return .accept
}
if let directionWord = context.args.scanWord() {
guard let direction = Direction(rawValue: directionWord) else {
context.send("Expected link or direction.")
return .accept
}
guard let neighborLink = currentRoom.exits[direction] else {
context.send("There's no room in that direction from you.")
return .accept
}
guard let neighborRoom = currentRoom.resolveLink(link: neighborLink) else {
context.send("Can't find neighbor room.")
return .accept
}
room = neighborRoom
} else {
room = currentRoom
}
}
var fields = [(title: String, content: String)]()
fields.append((title: "Link", content: "\(Link(room: room))"))
for direction in Direction.orderedDirections {
let directionName = direction.rawValue.capitalizingFirstLetter()
let directionLink = room.exits[direction]?.description ?? "none"
fields.append((title: directionName, content: directionLink))
}
context.send(fields.map{ "\($0.title): \($0.content)" }.joined(separator: "\n"))
return .accept
}
func room(context: CommandContext) -> CommandAction {
var result = ""
if let subcommand = context.args.scanWord() {
result += "Unknown subcommand: \(subcommand)\n"
}
result += "Available subcommands: delete, list, new, rename"
return .showUsage(result)
}
func dig(_ direction: Direction, _ context: CommandContext) -> CommandAction {
return dig(direction: direction, context: context)
}
func dig(direction: Direction, context: CommandContext) -> CommandAction {
guard let player = context.creature as? Player else { return .next }
guard let currentRoom = context.creature.room else {
context.send("You are not standing in any room, there's nowhere to dig.")
return .accept
}
guard player.editedInstances.contains(currentRoom.areaInstance) else {
context.send("Editing is disabled on this area instance. Consider 'area edit' and 'area build' commands to enter editing mode.")
return .accept
}
guard let roomId = context.args.scanWord() else {
context.send("Expected room identifier.")
return .accept
}
guard let destinationRoom = currentRoom.areaInstance.digRoom(from: currentRoom, direction: direction, id: roomId) else {
context.send("Failed to dig room.")
return .accept
}
context.creature.room = destinationRoom
context.creature.look()
return .accept
}
func dig(context: CommandContext) -> CommandAction {
var result = ""
if let subcommand = context.args.scanWord() {
result += "Unknown subcommand: \(subcommand)\n"
}
result += "Available subcommands:\n"
result += " north <room id>\n";
result += " south <room id>\n";
result += " east <room id>\n";
result += " west <room id>\n";
result += " up <room id>\n";
result += " down <room id>";
return .showUsage(result)
}
}
| apache-2.0 | deaf9ff11fce0f096b12faebe95f4cdf | 36.166667 | 147 | 0.585719 | 4.510892 | false | false | false | false |
daxrahusen/Eindproject | Social Wall/DetailSocialCell.swift | 1 | 3437 | //
// DetailSocialCell.swift
// Social Wall
//
// Created by Dax Rahusen on 14/01/2017.
// Copyright © 2017 Dax. All rights reserved.
//
import UIKit
import Firebase
class DetailSocialCell: SocialCell {
override var message: Message? {
didSet {
updateContent()
}
}
lazy var likeImageButton: UIButton = {
let button = UIButton()
button.setImage(UIImage(named: "heartNot"), for: .normal)
button.imageView?.layer.cornerRadius = 30
button.setTitleColor(.white, for: .normal)
button.tag = 0
button.imageView?.layer.masksToBounds = true
button.addTarget(self, action: #selector(likeButtonClicked(sender:)), for: .touchUpInside)
return button
}()
let likeCountLabel: UILabel = {
let label = UILabel()
label.textColor = .white
return label
}()
var detailController: DetailWallController?
weak var delegate: DetailWallControllerDelegate?
override func setupViews() {
super.setupViews()
messageImageView.isUserInteractionEnabled = true
messageImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(messageImageViewClicked(gesture:))))
addSubview(likeImageButton)
likeImageButton.addSubview(likeCountLabel)
addConstraintsWithFormat(format: "V:|-72-[v0(60)]", views: likeImageButton)
addConstraintsWithFormat(format: "H:[v0(60)]-16-|", views: likeImageButton)
likeImageButton.addConstraintsWithFormat(format: "H:|-24-[v0]|", views: likeCountLabel)
likeImageButton.addConstraintsWithFormat(format: "V:|[v0]|", views: likeCountLabel)
}
func likeButtonClicked(sender: UIButton) {
delegate?.likeButtonClicked(state: sender.tag)
}
func messageImageViewClicked(gesture: UITapGestureRecognizer) {
if let imageView = gesture.view as? UIImageView {
delegate?.zoomImageViewClicked(startingImageView: imageView)
}
}
private func updateContent() {
if let username = message?.username {
profileUsername.text = username
}
if let userImageUrl = message?.userImageUrl {
profileImageView.loadImageUsingCacheWithUrlString(urlString: userImageUrl)
}
if let time = message?.dateTime {
let date = Date(timeIntervalSince1970: time)
messageDate.text = date.toReadableText()
}
if let messageImage = message?.messageImageUrl {
messageImageView.loadImageUsingCacheWithUrlString(urlString: messageImage)
}
if let content = message?.content {
messageTextView.text = content
}
if let likes = message?.likes {
likeCountLabel.text = likes.count > 0 ? "\(likes.count)" : ""
if let uid = FIRAuth.auth()?.currentUser?.uid {
if likes.contains(uid) {
likeImageButton.tag = 1
likeImageButton.setImage(UIImage(named: "heart"), for: .normal)
} else {
likeImageButton.tag = 0
likeImageButton.setImage(UIImage(named: "heartNot"), for: .normal)
}
}
}
}
}
| apache-2.0 | dd20d5be121bdbbd24b2630e32d94245 | 31.415094 | 137 | 0.597497 | 5.120715 | false | false | false | false |
GTMYang/GTMRouter | GTMRouter/Router.swift | 1 | 2699 | //
// Router.swift
// GTMRouter
//
// Created by luoyang on 2016/12/19.
// Copyright © 2016年 luoyang. All rights reserved.
//
import Foundation
public class Router {
private init(helper: GRHelper = DefaultHelper()) {
self.helper = helper
}
var helper: GRHelper
var webVCFactory: WebVCFactory?
static let shared: Router = {
return Router()
}()
func push(url: String, parameter: [String: Any]?) {
self.open(urlString: url, parameter: parameter, modal: false)
}
func present(url: String, parameter: [String: Any]?) {
self.open(urlString: url, parameter: parameter, modal: true)
}
// MARK: - Private
func open(urlString: String, parameter: [String: Any]?, modal: Bool) {
if let controller = self.controller(from: urlString, parameter: parameter) {
if modal {
helper.topViewController?.present(controller, animated: true, completion: nil)
} else {
helper.navigationController?.pushViewController(controller, animated: true)
}
}
}
func controller(from urlString: String, parameter: [String: Any]? = nil) -> UIViewController? {
if let url = urlString.asURL(), let target = url.host {
if let scheme = url.scheme,
(scheme == "http" || scheme == "https") {
// Web View Controller
let webController: UIViewController? = self.webVCFactory?.createWebVC(with: urlString, parameter: parameter ?? [:])
return webController
} else {
// controller
let path = url.path.replacingOccurrences(of: "/", with: "")
let className = "\(target).\(path)"
let cls: AnyClass? = NSClassFromString(className)
if let controller = cls as? UIViewController.Type {
let viewController: UIViewController = controller.init()
// parameter
viewController.initQueryParameters(parameters: url.queryParameters)
if let dicParameters = parameter {
viewController.initliazeDicParameters(parameters: dicParameters)
}
return viewController
} else {
print(false, "Router ---> \(className) 必须是UIViewController类型或者其子类型")
}
}
} else {
print(false, "Router ---> url.host不能为空,必须为类所在的Target Name")
}
return nil
}
}
| mit | 8971121fad216462ae3d5635bfd82c35 | 33.868421 | 131 | 0.54566 | 5.038023 | false | false | false | false |
benlangmuir/swift | test/SILOptimizer/super_init.swift | 10 | 1919 | // RUN: %target-swift-frontend -emit-sil %s | %FileCheck %s
// CHECK-LABEL: sil hidden [exact_self_class] [noinline] @$s10super_init3FooCyACSicfC : $@convention(method) (Int, @thick Foo.Type) -> @owned Foo
// CHECK-NOT: class_method
// CHECK-NOT: super_method
// CHECK: [[SUPER_INIT:%.*]] = function_ref @$s10super_init3FooCyACSicfc
// CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]
// CHECK-LABEL: sil hidden [noinline] @$s10super_init3BarC{{[_0-9a-zA-Z]*}}fc
// CHECK-NOT: super_method
// CHECK: function_ref @$s10super_init3FooCACycfc
class Foo {
@inline(never)
init() {}
@inline(never)
init(_ x: Foo) {}
@inline(never)
init(_ x: Int) {}
}
class Bar: Foo {
@inline(never)
override init() {
super.init()
}
}
extension Foo {
@inline(never)
convenience init(x: Int) {
self.init()
}
}
class Zim: Foo {
var foo = Foo()
// CHECK-LABEL: sil hidden @$s10super_init3ZimC{{[_0-9a-zA-Z]*}}fc
// CHECK-NOT: super_method {{%[0-9]+}} : $Zim, #Foo.init!initializer
// CHECK: function_ref @$s10super_init3FooCACycfC
// CHECK: function_ref @$s10super_init3FooCACycfc
}
class Zang: Foo {
var foo: Foo
@inline(never)
override init() {
foo = Foo()
super.init()
}
// CHECK-LABEL: sil hidden [noinline] @$s10super_init4ZangCACycfc
// CHECK-NOT: super_method {{%[0-9]+}} : $Zang, #Foo.init!initializer
// CHECK: function_ref @$s10super_init3FooCACycfC
// CHECK: function_ref @$s10super_init3FooCACycfc
}
class Good: Foo {
let x: Int
// CHECK-LABEL: sil hidden [noinline] @$s10super_init4GoodCACycfc
// CHECK-NOT: super_method {{%[0-9]+}} : $Good, #Foo.init!initializer
// CHECK: [[SUPER_INIT:%.*]] = function_ref @$s10super_init3FooCyACSicfc
// CHECK: apply [[SUPER_INIT]]
@inline(never)
override init() {
x = 10
super.init(x)
}
}
| apache-2.0 | 0ede53036747abd3ab18ba0162beca65 | 26.414286 | 145 | 0.602397 | 3.075321 | false | false | false | false |
yoavlt/PeriscommentView | PeriscommentView/PeriscommentUtils.swift | 1 | 2646 | //
// PeriscommentView.swift
// PeriscommentView
//
// Created by Takuma Yoshida on 2015/04/10.
// Copyright (c) 2015 Uniface, Inc. All rights reserved.
//
import UIKit
class ColorGenerator {
let red = UIColor(red: 0.96, green: 0.26, blue: 0.21, alpha: 0.7)
let pink = UIColor(red: 0.91, green: 0.12, blue: 0.38, alpha: 0.7)
let purple = UIColor(red: 0.61, green: 0.15, blue: 0.69, alpha: 0.7)
let blue = UIColor(red: 0.12, green: 0.59, blue: 0.95, alpha: 0.7)
let green = UIColor(red: 0.3, green: 0.69, blue: 0.31, alpha: 0.7)
let yellow = UIColor(red: 1.0, green: 0.92, blue: 0.23, alpha: 0.7)
let orange = UIColor(red: 1.0, green: 0.60, blue: 0, alpha: 0.7)
func pick() -> UIColor {
let colors = [red, pink, purple, blue, green, yellow, orange]
let index = arc4random_uniform(UInt32(colors.count))
return colors[Int(index)]
}
}
struct PeriscommentConfig {
let layout: PeriscommentLayout
let commentFont = PeriscommentFont(font: UIFont.systemFont(ofSize: 14.0), color: UIColor.black)
let nameFont = PeriscommentFont(font: UIFont.systemFont(ofSize: 12.0), color: UIColor.lightGray)
let disappearDuration = 6.0
let appearDuration = 1.0
init() {
self.layout = PeriscommentLayout()
}
}
struct PeriscommentLayout {
let offset: CGFloat = 10.0
let padding: CGFloat = 2.5
let commentSpace: CGFloat = 1.5
let cellSpace: CGFloat = 4.0
let maximumWidth: CGFloat = 200.0
let markWidth: CGFloat = 40.0
let allowLineBreak = true
let backgroundColor = UIColor.clear
init() {
}
func maxCommentWidth() -> CGFloat {
return self.maximumWidth - (self.padding * 2 + self.markWidth + self.offset)
}
}
struct PeriscommentFont {
let font: UIFont
let color: UIColor
}
class CommentLabel : UILabel {
var allowLineBreak: Bool
let maxCommentWidth: CGFloat
init(frame: CGRect, font: PeriscommentFont, allowLineBreak: Bool, maxWidth: CGFloat) {
self.allowLineBreak = allowLineBreak
self.maxCommentWidth = maxWidth
super.init(frame: frame)
self.textColor = font.color
self.font = font.font
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func sizeToFit() {
if allowLineBreak {
self.lineBreakMode = NSLineBreakMode.byWordWrapping
self.numberOfLines = 0
}
super.sizeToFit()
self.frame.size.width = min(maxCommentWidth, self.frame.size.width)
super.sizeToFit()
}
}
| mit | 8d15bcdec3fbcb7bbb929f0ab8e26c73 | 28.730337 | 100 | 0.636432 | 3.556452 | false | false | false | false |
iAugux/ENSwiftSideMenu | ENSwiftSideMenu/Library/ENSideMenu.swift | 1 | 13536 | //
// SideMenu.swift
// SwiftSideMenu
//
// Created by Evgeny on 24.07.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
@objc public protocol ENSideMenuDelegate {
optional func sideMenuWillOpen()
optional func sideMenuWillClose()
optional func sideMenuShouldOpenSideMenu () -> Bool
}
@objc public protocol ENSideMenuProtocol {
var sideMenu : ENSideMenu? { get }
func setContentViewController(contentViewController: UIViewController)
func dismissViewOpen()
func dismissViewClose()
}
public enum ENSideMenuAnimation : Int {
case None
case Default
}
public enum ENSideMenuPosition : Int {
case Left
case Right
}
extension UIViewController {
public func toggleSideMenuView () {
sideMenuController()?.sideMenu?.toggleMenu()
if isSideMenuOpen() {
sideMenuController()?.dismissViewOpen()
}
else{
sideMenuController()?.dismissViewClose()
}
}
public func hideSideMenuView () {
sideMenuController()?.sideMenu?.hideSideMenu()
// sideMenuController()?.dismissViewClose()
}
public func showSideMenuView () {
sideMenuController()?.sideMenu?.showSideMenu()
// sideMenuController()?.dismissViewOpen()
}
public func isSideMenuOpen () -> Bool {
let sieMenuOpen = self.sideMenuController()?.sideMenu?.isMenuOpen
return sieMenuOpen!
}
/**
* You must call this method from viewDidLayoutSubviews in your content view controlers so it fixes size and position of the side menu when the screen
* rotates.
* A convenient way to do it might be creating a subclass of UIViewController that does precisely that and then subclassing your view controllers from it.
*/
func fixSideMenuSize() {
if let navController = self.navigationController as? ENSideMenuNavigationController {
navController.sideMenu?.updateFrame()
}
}
public func sideMenuController () -> ENSideMenuProtocol? {
var iteration : UIViewController? = self.parentViewController
if (iteration == nil) {
return topMostController()
}
repeat {
if (iteration is ENSideMenuProtocol) {
return iteration as? ENSideMenuProtocol
} else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) {
iteration = iteration!.parentViewController
} else {
iteration = nil
}
} while (iteration != nil)
return iteration as? ENSideMenuProtocol
}
internal func topMostController () -> ENSideMenuProtocol? {
var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topController?.presentedViewController is ENSideMenuProtocol) {
topController = topController?.presentedViewController
}
return topController as? ENSideMenuProtocol
}
}
public class ENSideMenu : NSObject, UIGestureRecognizerDelegate {
public var menuWidth : CGFloat = 160.0 {
didSet {
needUpdateApperance = true
updateFrame()
}
}
private var menuPosition:ENSideMenuPosition = .Left
public var bouncingEnabled :Bool = true
public var animationDuration = 0.4
private let sideMenuContainerView = UIView()
private var menuViewController : UIViewController!
private var animator : UIDynamicAnimator!
private var sourceView : UIView!
private var needUpdateApperance : Bool = false
public weak var delegate : ENSideMenuDelegate?
private(set) var isMenuOpen : Bool = false
public var allowLeftSwipe : Bool = true
public var allowRightSwipe : Bool = true
public init(sourceView: UIView, menuPosition: ENSideMenuPosition) {
super.init()
self.sourceView = sourceView
self.menuPosition = menuPosition
self.setupMenuView()
animator = UIDynamicAnimator(referenceView:sourceView)
// Add right swipe gesture recognizer
let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
rightSwipeGestureRecognizer.delegate = self
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
// Add left swipe gesture recognizer
let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
leftSwipeGestureRecognizer.delegate = self
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
if (menuPosition == .Left) {
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
else {
sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
sourceView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
}
public convenience init(sourceView: UIView, menuViewController: UIViewController, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
self.menuViewController = menuViewController
self.menuViewController.view.frame = sideMenuContainerView.bounds
self.menuViewController.view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(self.menuViewController.view)
}
public convenience init(sourceView: UIView, view: UIView, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
view.frame = sideMenuContainerView.bounds
view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(view)
}
/**
* Do not make this function private, it must be called from your own UIViewControllers (using the fixSideMenuSize function of the extension).
*/
func updateFrame() {
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
let menuFrame = CGRectMake(
(menuPosition == .Left) ?
isMenuOpen ? 0 : -menuWidth-1.0 :
isMenuOpen ? width - menuWidth : width+1.0,
sourceView.frame.origin.y,
menuWidth,
height
)
sideMenuContainerView.frame = menuFrame
}
private func adjustFrameDimensions( width: CGFloat, height: CGFloat ) -> (CGFloat,CGFloat) {
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 &&
(UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeRight ||
UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeLeft) {
// iOS 7.1 or lower and landscape mode -> interchange width and height
return (height, width)
}
else {
return (width, height)
}
}
private func setupMenuView() {
// Configure side menu container
updateFrame()
sideMenuContainerView.backgroundColor = UIColor.clearColor()
sideMenuContainerView.clipsToBounds = false
sideMenuContainerView.layer.masksToBounds = false
sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0)
sideMenuContainerView.layer.shadowRadius = 1.0
sideMenuContainerView.layer.shadowOpacity = 0.125
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
sourceView.addSubview(sideMenuContainerView)
if (NSClassFromString("UIVisualEffectView") != nil) {
// Add blur view
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = sideMenuContainerView.bounds
visualEffectView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(visualEffectView)
}
else {
// TODO: add blur for ios 7
}
}
private func toggleMenu (shouldOpen: Bool) {
if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) {
return
}
updateSideMenuApperanceIfNeeded()
isMenuOpen = shouldOpen
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
if (bouncingEnabled) {
animator.removeAllBehaviors()
var gravityDirectionX: CGFloat
var pushMagnitude: CGFloat
var boundaryPointX: CGFloat
var boundaryPointY: CGFloat
if (menuPosition == .Left) {
// Left side menu
gravityDirectionX = (shouldOpen) ? 1 : -1
pushMagnitude = (shouldOpen) ? 20 : -20
boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2
boundaryPointY = 20
}
else {
// Right side menu
gravityDirectionX = (shouldOpen) ? -1 : 1
pushMagnitude = (shouldOpen) ? -20 : 20
boundaryPointX = (shouldOpen) ? width-menuWidth : width+menuWidth+2
boundaryPointY = -20
}
let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView])
collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY),
toPoint: CGPointMake(boundaryPointX, height))
animator.addBehavior(collisionBehavior)
let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = pushMagnitude
animator.addBehavior(pushBehavior)
let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView])
menuViewBehavior.elasticity = 0.25
animator.addBehavior(menuViewBehavior)
}
else {
var destFrame :CGRect
if (menuPosition == .Left) {
destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, height)
}
else {
destFrame = CGRectMake((shouldOpen) ? width-menuWidth : width+2.0,
0,
menuWidth,
height)
}
UIView.animateWithDuration(animationDuration, animations: { () -> Void in
self.sideMenuContainerView.frame = destFrame
})
}
if (shouldOpen) {
delegate?.sideMenuWillOpen?()
menuViewController.sideMenuController()?.dismissViewOpen()
} else {
delegate?.sideMenuWillClose?()
menuViewController.sideMenuController()?.dismissViewClose()
}
}
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UISwipeGestureRecognizer {
let swipeGestureRecognizer = gestureRecognizer as! UISwipeGestureRecognizer
if !self.allowLeftSwipe {
if swipeGestureRecognizer.direction == .Left {
return false
}
}
if !self.allowRightSwipe {
if swipeGestureRecognizer.direction == .Right {
return false
}
}
}
return true
}
internal func handleGesture(gesture: UISwipeGestureRecognizer) {
toggleMenu((self.menuPosition == .Right && gesture.direction == .Left)
|| (self.menuPosition == .Left && gesture.direction == .Right))
}
private func updateSideMenuApperanceIfNeeded () {
if (needUpdateApperance) {
var frame = sideMenuContainerView.frame
frame.size.width = menuWidth
sideMenuContainerView.frame = frame
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
needUpdateApperance = false
}
}
public func toggleMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
else {
updateSideMenuApperanceIfNeeded()
toggleMenu(true)
}
}
public func showSideMenu () {
if (!isMenuOpen) {
toggleMenu(true)
}
}
public func hideSideMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
}
}
| mit | cd18387843b6ec5f053e581958c4a3e1 | 35.782609 | 157 | 0.623596 | 6.122117 | false | false | false | false |
pyromobile/nubomedia-ouatclient-src | ios/LiveTales/uoat/FriendsManagerViewController.swift | 1 | 12199 | //
// FriendsManagerViewController.swift
// uoat
//
// Created by Pyro User on 2/6/16.
// Copyright © 2016 Zed. All rights reserved.
//
import UIKit
class FriendsManagerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, AddFriendDelegate, NotificationAcceptedDelegate, FriendsListDelegate
{
weak var user:User!
var notificationsByType:[NotificationType:[Notification]]!
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(FriendsManagerViewController.networkStatusChanged(_:)), name: NetworkWatcher.reachabilityStatusChangedNotification, object: nil)
}
deinit
{
self.user = nil
NSNotificationCenter.defaultCenter().removeObserver( self, name: NetworkWatcher.reachabilityStatusChangedNotification, object: nil )
print("FriendsManagerViewController - deInit....OK")
}
override func viewDidLoad()
{
super.viewDidLoad()
self.friendsTableView.delegate = self
self.friendsTableView.dataSource = self
self.loadFriends()
self.findNotifications()
// Do any additional setup after loading the view.
//load resources.
//.:Back button
let leftArrowActiveImage:UIImage = Utils.flipImage( named: "btn_next_available", orientation: .Down )
self.leftArrowImage.image = leftArrowActiveImage
//Head title.
let headAttrString = NSMutableAttributedString(string: self.headerLabel.text!,
attributes: [NSStrokeWidthAttributeName: -7.0,
NSFontAttributeName: UIFont(name: "ArialRoundedMTBold", size: 22)!,
NSStrokeColorAttributeName: UIColor.whiteColor(),
NSForegroundColorAttributeName: self.headerLabel.textColor ])
self.headerLabel.attributedText! = headAttrString
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if( segue.identifier == "showAddFriendView" )
{
let controller = segue.destinationViewController as! AddFriendViewController;
controller.user = self.user
controller.addFriendDelegate = self
}
else if( segue.identifier == "showNotificationsManagerView" )
{
let controller = segue.destinationViewController as! NotificationsManagerViewController;
controller.user = self.user
controller.notifications = self.notificationsByType[NotificationType.FriendShip]
controller.notificationAcceptedDelegate = self
}
else if( segue.identifier == "showFriendsListManagerView" )
{
let controller = segue.destinationViewController as! FriendsListManagerViewController;
controller.user = self.user
controller.friends = self.friends
controller.friendsListDelegate = self
}
}
func networkStatusChanged(notification:NSNotification)
{
print("FriendsManagerViewController::networkStatusChanged was called...")
if( NetworkWatcher.internetAvailabe )
{
Utils.alertMessage( self, title:"Notice", message:"Internet connection works again!", onAlertClose:nil )
}
else
{
Utils.alertMessage( self, title:"Attention", message:"Internet connection lost!", onAlertClose:nil )
}
}
/*=============================================================*/
/* from UITableViewDataSource */
/*=============================================================*/
func numberOfSectionsInTableView(tableView:UITableView) -> Int
{
return 1
}
func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return self.friends.count;
}
func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier( self.cellIdentifier, forIndexPath:indexPath ) as! FriendsTableViewCell
let row = indexPath.row
//User information.
let friend:(id:String,nick:String,isPending:Bool) = self.friends[row]
cell.imageView?.image = UIImage() //TODO: foto usuario??
cell.nickNameLabel.text = friend.nick
if( friend.isPending )
{
cell.nickNameLabel.textColor = UIColor.lightGrayColor()
}
return cell
}
/*=============================================================*/
/* from UITableViewDelegate */
/*=============================================================*/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
cell.backgroundColor = .clearColor()
}
/*=============================================================*/
/* from AddFriendDelegate */
/*=============================================================*/
func addPendingFriend( nickName:String )
{
let friend:(id:String,nick:String,isPending:Bool) = (id:"",nick:nickName,isPending:true)
self.friends.append(friend)
self.friendsTableView.reloadData()
}
/*=============================================================*/
/* from NotificationAcceptedDelegate */
/*=============================================================*/
func addNewFriends(notifications:[Notification])
{
for notification:Notification in notifications
{
let friend:(id:String,nick:String,isPending:Bool) = (id:notification.getTo(),nick:notification.nickNameFrom,isPending:false)
self.friends.append(friend)
var pos:Int = 0
let found:Bool = (self.notificationsByType[NotificationType.FriendShip]?.contains({(item) -> Bool in
let found = item.getId() == notification.getId()
if(!found)
{
pos += 1
}
return found
}))!
if( found )
{
self.notificationsByType[NotificationType.FriendShip]?.removeAtIndex( pos )
}
}
self.friendsTableView.reloadData()
self.findNotifications()
}
/*=============================================================*/
/* from NotificationAcceptedDelegate */
/*=============================================================*/
func updatedFriendsList(friends:[(id:String, nick:String, isPending:Bool)])
{
self.friends = friends
self.friendsTableView.reloadData()
}
/*=============================================================*/
/* UI Section */
/*=============================================================*/
@IBOutlet weak var leftArrowImage: UIImageView!
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var friendsTableView: UITableView!
@IBOutlet weak var notificationButton: UIButton!
@IBOutlet weak var bgNotificationImage: UIImageView!
@IBOutlet weak var notificationCountLabel: UILabel!
//---------------------------------------------------------------
// UI Actions
//---------------------------------------------------------------
@IBAction func back(sender: UIButton)
{
self.dismissViewControllerAnimated(true, completion: {})
}
@IBAction func addFriend(sender: AnyObject)
{
if( NetworkWatcher.internetAvailabe )
{
performSegueWithIdentifier("showAddFriendView", sender: nil)
}
else
{
Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
}
}
@IBAction func editFriends(sender: AnyObject)
{
if( NetworkWatcher.internetAvailabe )
{
performSegueWithIdentifier("showFriendsListManagerView", sender: nil)
}
else
{
Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
}
}
@IBAction func notifications(sender: AnyObject)
{
if( NetworkWatcher.internetAvailabe )
{
performSegueWithIdentifier("showNotificationsManagerView", sender: nil)
}
else
{
Utils.alertMessage( self, title:"Attention", message:"You must have internet connection!", onAlertClose:nil )
}
}
/*=============================================================*/
/* Private Section */
/*=============================================================*/
private func loadFriends()
{
UserModel.loadUserFriends(self.user.id) { [weak self](friends) in
if( friends == nil )
{
print("Error to get friends...")
}
else
{
for friend in friends!
{
let friend:(id:String,nick:String,isPending:Bool) = (id:friend.id,nick:friend.nick,isPending:false)
self!.friends.append( friend )
}
NotificationModel.getNotificationsSentByMe(self!.user.id, onNotificationsReady: { (notifications) in
if let notificationsFriendship:[Notification] = notifications[NotificationType.FriendShip]
{
NotificationModel.getNickNamesFromSentNotifications(notificationsFriendship, onNotificationsReady: { [weak self] (notifications) in
for notification:Notification in notifications
{
if( notification.getFrom() == "pub_\(self!.user.id)" )
{
let friend:(id:String,nick:String,isPending:Bool) = (id:notification.getFrom(),nick:notification.nickNameFrom,isPending:true)
self!.friends.append( friend )
}
}
self!.friendsTableView.reloadData()
})
}
})
}
self!.friendsTableView.reloadData()
}
}
private func findNotifications()
{
//Busco las notificaciones que recivo y las que he mandado yo (para dibujarlas como pendientes).
//{$or:[{"to":"pub_573b1d53e4b04c6b97862081"},{"from":"pub_573b1d53e4b04c6b97862081"}]}
let haveNotifications:Bool = self.notificationsByType[NotificationType.FriendShip]?.count > 0
self.notificationButton.enabled = haveNotifications
self.bgNotificationImage.hidden = !haveNotifications
self.notificationCountLabel.hidden = !haveNotifications
if( haveNotifications )
{
let notificationCount:Int = (self.notificationsByType[NotificationType.FriendShip]?.count)!
self.notificationCountLabel.text = "\(notificationCount)"
}
}
private let cellIdentifier:String = "FriendsTableViewCell"
private var friends:[(id:String,nick:String,isPending:Bool)] = [(id:String,nick:String,isPending:Bool)]()
}
| apache-2.0 | 2f57f797ac63240e922852f3917e85ab | 37.72381 | 211 | 0.546073 | 5.958964 | false | false | false | false |
mahuiying0126/MDemo | BangDemo/BangDemo/Modules/Personal/Down/control/MSelectDownViewController.swift | 1 | 7512 | //
// MSelectDownViewController.swift
// BangDemo
//
// Created by yizhilu on 2017/8/21.
// Copyright © 2017年 Magic. All rights reserved.
//
import UIKit
class MSelectDownViewController: UIViewController,CourseListDelegate {
/** *下载列表数据 */
var selectList : Array<Any>?
/** *课程图片 */
var imageUrl : String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = Whit
self.title = "下载列表"
createFoot()
self.tableView.CourseListData(self.selectList!)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
for item in self.selectList! {
let listModel = item as! DetailCourseListModel
for currentItem in listModel.childKpoints! {
let model = currentItem as! DetailCourseChildModel
model.isSelected = false
}
}
self.tableView.CourseListData(self.selectList!)
}
@objc func downButtonEvent(sender:UIButton){
// if sender.tag == 0 {
//
// }else{
//
// }
///开始下载
let downView = MDownViewController.shareInstance
self.navigationController?.pushViewController(downView, animated: true)
}
///点击代理
func didSelectCourseList(index : IndexPath , model : DetailCourseChildModel){
// let tempUrl = ["d96f8e8d3ac033673695df6d192ce4b7","86029f91b95721adae004393f1848ca5","9b430dc1efd1b40ab90cc230a19511b6"]
if !model.isSelected {
if MNetworkUtils.isNoNet() {
///没有网络
MBProgressHUD.showMBPAlertView("已于网络断开连接", withSecond: 2.0)
return
}
let isDownloading = MFMDBTool.shareInstance.cheackFromDownloadingTableIsExist(model.ID!)
if isDownloading {
MBProgressHUD.showMBPAlertView("正在下载中", withSecond: 1.5)
return
}
let isFinsh = MFMDBTool.shareInstance.cheackFromFinshTableIsExist(model.ID!)
if isFinsh {
MBProgressHUD.showMBPAlertView("下载已完成", withSecond: 1.5)
return
}
let checkResultDict = model.ID?.checkPointIsAbleToPlay()
if (checkResultDict != nil) {
let entity = checkResultDict?["entity"]
let fileStyle = entity?["fileType"]
let videoStyle = entity?["videoType"]
if MNetworkUtils.isEnableWWAN() {
///4G网络下
let alertControl = UIAlertController.init(title: "提示", message: "当前4G网络是否下载?", preferredStyle: .alert)
let allow = UIAlertAction.init(title: "是", style: .default, handler: { (action) in
model.isSelected = !model.isSelected
///将要下载的 model 转化为 downModel
let downModel = DownloadingModel.conversionsModel(model)
downModel.videoType = videoStyle?.rawString()//96K
downModel.fileType = fileStyle?.rawString()//Video
downModel.videoUrl = entity?["videoUrl"].string
downModel.imageUrl = self.imageUrl
MFMDBTool.shareInstance.addDownloadingModel(downModel)
})
let cancel = UIAlertAction.init(title: "否", style: .cancel, handler: nil)
alertControl.addAction(allow)
alertControl.addAction(cancel)
self.present(alertControl, animated: true, completion: nil)
}else{
///wifi下
model.isSelected = !model.isSelected
///将要下载的 model 转化为 downModel
let downModel = DownloadingModel.conversionsModel(model)
downModel.videoType = videoStyle?.rawString()//96K
downModel.fileType = fileStyle?.rawString()//Video
downModel.videoUrl = entity?["videoUrl"].string
// downModel.videoUrl = tempUrl[index.row]
downModel.imageUrl = self.imageUrl
MFMDBTool.shareInstance.addDownloadingModel(downModel)
}
}else{
MBProgressHUD.showMBPAlertView("该视频暂时无法下载", withSecond: 1.0)
}
}
else{
MFMDBTool.shareInstance.removeDownloadingModel(model.ID!)
MBProgressHUD.showMBPAlertView("已从下载列表中移除", withSecond: 1.5)
}
self.tableView.reloadRows(at: [index], with: .none)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// 课程列表
lazy var tableView : DetailCourseListView = {
let tempList = DetailCourseListView(frame: CGRect.init(x: 0, y: 0, width: Screen_width, height: Screen_height - 64 - 60), style: UITableViewStyle.plain)
self.view.addSubview(tempList)
tempList.isSelectView = true
tempList.cellID = "select"
tempList.courseDelegate = self
return tempList
}()
private func createFoot(){
let footView = UIView.init(frame: .init(x: 0, y: Screen_height - 64 - 60, width: Screen_width, height: 60))
self.view.addSubview(footView)
footView.backgroundColor = Whit
let line = UIView.init(frame: .init(x: 0, y: 0, width: Screen_width, height: 1))
line.backgroundColor = UIColorFromRGB(0xd2d2d2)
footView.addSubview(line)
let line1 = UIView.init(frame: .init(x: Screen_width / 2 - 0.5, y: 15, width: 0.5, height: 30))
line1.backgroundColor = UIColorFromRGB(0xd2d2d2)
footView.addSubview(line1)
let iconArr = ["查看缓存","查看下载"]
for (index,item) in iconArr.enumerated() {
let downButton = UIButton().buttonTitle(title: item, image: item, selectImage: item, backGroundColor: Whit, Frame: CGRect.init(x: (Screen_width/2) * CGFloat(index) , y: 12 , width: Screen_width / 2 - 3 , height: 40))
downButton.setTitleColor(UIColorFromRGB(0x333333), for: .normal)
downButton.titleLabel?.font = FONT(15)
downButton.layoutButtonWithEdgeInsetsStyle(style: .imageTop, imageTitleSpace: 3)
downButton.tag = index
downButton.addTarget(self, action: #selector(downButtonEvent(sender:)), for: .touchUpInside)
footView.addSubview(downButton)
}
}
deinit {
MYLog("下载选择页面销毁")
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f3de63cfd32f3e9bd849c70153faf05b | 39.005495 | 229 | 0.585771 | 4.480615 | false | false | false | false |
place-marker/ios_google_places_autocomplete | GooglePlacesAutocomplete/GooglePlacesAutocomplete.swift | 1 | 10450 | //
// GooglePlacesAutocomplete.swift
// GooglePlacesAutocomplete
//
// Created by Howard Wilson on 10/02/2015.
// Copyright (c) 2015 Howard Wilson. All rights reserved.
//
import UIKit
public enum PlaceType: Printable {
case All
case Geocode
case Address
case Establishment
case Regions
case Cities
public var description : String {
switch self {
case .All: return ""
case .Geocode: return "geocode"
case .Address: return "address"
case .Establishment: return "establishment"
case .Regions: return "(regions)"
case .Cities: return "(cities)"
}
}
}
public class Place: NSObject {
public let id: String
public let desc: String
public var apiKey: String?
override public var description: String {
get { return desc }
}
public init(id: String, description: String) {
self.id = id
self.desc = description
}
public convenience init(prediction: [String: AnyObject], apiKey: String?) {
self.init(
id: prediction["place_id"] as String,
description: prediction["description"] as String
)
self.apiKey = apiKey
}
/**
Call Google Place Details API to get detailed information for this place
Requires that Place#apiKey be set
:param: result Callback on successful completion with detailed place information
*/
public func getDetails(result: PlaceDetails -> ()) {
GooglePlaceDetailsRequest(place: self).request(result)
}
}
public class PlaceDetails: Printable {
public let name: String
public let latitude: Double
public let longitude: Double
public let raw: [String: AnyObject]
public init(json: [String: AnyObject]) {
let result = json["result"] as [String: AnyObject]
let geometry = result["geometry"] as [String: AnyObject]
let location = geometry["location"] as [String: AnyObject]
self.name = result["name"] as String
self.latitude = location["lat"] as Double
self.longitude = location["lng"] as Double
self.raw = json
}
public var description: String {
return "PlaceDetails: \(name) (\(latitude), \(longitude))"
}
}
@objc public protocol GooglePlacesAutocompleteDelegate {
optional func placesFound(places: [Place])
optional func placeSelected(place: Place)
optional func placeViewClosed()
}
// MARK: - GooglePlacesAutocomplete
public class GooglePlacesAutocomplete: UINavigationController {
public var gpaViewController: GooglePlacesAutocompleteContainer!
public var closeButton: UIBarButtonItem!
public var placeDelegate: GooglePlacesAutocompleteDelegate? {
get { return gpaViewController.delegate }
set { gpaViewController.delegate = newValue }
}
public convenience init(apiKey: String, placeType: PlaceType = .All) {
let gpaViewController = GooglePlacesAutocompleteContainer(
apiKey: apiKey,
placeType: placeType
)
self.init(rootViewController: gpaViewController)
self.gpaViewController = gpaViewController
closeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: "close")
closeButton.style = UIBarButtonItemStyle.Done
gpaViewController.navigationItem.leftBarButtonItem = closeButton
gpaViewController.navigationItem.title = "Enter Address"
}
func close() {
placeDelegate?.placeViewClosed?()
}
}
// MARK: - GooglePlacesAutocompleteContainer
public class GooglePlacesAutocompleteContainer: UIViewController {
@IBOutlet public weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var topConstraint: NSLayoutConstraint!
var delegate: GooglePlacesAutocompleteDelegate?
var apiKey: String?
var places = [Place]()
var placeType: PlaceType = .All
convenience init(apiKey: String, placeType: PlaceType = .All) {
let bundle = NSBundle(forClass: GooglePlacesAutocompleteContainer.self)
self.init(nibName: "GooglePlacesAutocomplete", bundle: bundle)
self.apiKey = apiKey
self.placeType = placeType
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override public func viewWillLayoutSubviews() {
topConstraint.constant = topLayoutGuide.length
}
override public func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
searchBar.becomeFirstResponder()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
func keyboardWasShown(notification: NSNotification) {
if isViewLoaded() && view.window != nil {
let info: Dictionary = notification.userInfo!
let keyboardSize: CGSize = (info[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue().size)!
let contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0)
tableView.contentInset = contentInsets;
tableView.scrollIndicatorInsets = contentInsets;
}
}
func keyboardWillBeHidden(notification: NSNotification) {
if isViewLoaded() && view.window != nil {
self.tableView.contentInset = UIEdgeInsetsZero
self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero
}
}
}
// MARK: - GooglePlacesAutocompleteContainer (UITableViewDataSource / UITableViewDelegate)
extension GooglePlacesAutocompleteContainer: UITableViewDataSource, UITableViewDelegate {
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return places.count
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
// Get the corresponding candy from our candies array
let place = self.places[indexPath.row]
// Configure the cell
cell.textLabel!.text = place.description
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.placeSelected?(self.places[indexPath.row])
}
}
// MARK: - GooglePlacesAutocompleteContainer (UISearchBarDelegate)
extension GooglePlacesAutocompleteContainer: UISearchBarDelegate {
public func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
if (searchText == "") {
self.places = []
tableView.hidden = true
} else {
getPlaces(searchText)
}
}
/**
Call the Google Places API and update the view with results.
:param: searchString The search query
*/
private func getPlaces(searchString: String) {
GooglePlacesRequestHelpers.doRequest(
"https://maps.googleapis.com/maps/api/place/autocomplete/json",
params: [
"input": searchString,
"types": placeType.description,
"key": apiKey ?? ""
]
) { json in
if let predictions = json["predictions"] as? Array<[String: AnyObject]> {
self.places = predictions.map { (prediction: [String: AnyObject]) -> Place in
return Place(prediction: prediction, apiKey: self.apiKey)
}
self.tableView.reloadData()
self.tableView.hidden = false
self.delegate?.placesFound?(self.places)
}
}
}
}
// MARK: - GooglePlaceDetailsRequest
class GooglePlaceDetailsRequest {
let place: Place
init(place: Place) {
self.place = place
}
func request(result: PlaceDetails -> ()) {
GooglePlacesRequestHelpers.doRequest(
"https://maps.googleapis.com/maps/api/place/details/json",
params: [
"placeid": place.id,
"key": place.apiKey ?? ""
]
) { json in
result(PlaceDetails(json: json as [String: AnyObject]))
}
}
}
// MARK: - GooglePlacesRequestHelpers
class GooglePlacesRequestHelpers {
/**
Build a query string from a dictionary
:param: parameters Dictionary of query string parameters
:returns: The properly escaped query string
*/
private class func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += [(escape(key), escape("\(value)"))]
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
private class func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue)
}
private class func doRequest(url: String, params: [String: String], success: NSDictionary -> ()) {
var request = NSMutableURLRequest(
URL: NSURL(string: "\(url)?\(query(params))")!
)
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request) { data, response, error in
self.handleResponse(data, response: response as? NSHTTPURLResponse, error: error, success: success)
}
task.resume()
}
private class func handleResponse(data: NSData!, response: NSHTTPURLResponse!, error: NSError!, success: NSDictionary -> ()) {
if let error = error {
println("GooglePlaces Error: \(error.localizedDescription)")
return
}
if response == nil {
println("GooglePlaces Error: No response from API")
return
}
if response.statusCode != 200 {
println("GooglePlaces Error: Invalid status code \(response.statusCode) from API")
return
}
var serializationError: NSError?
var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(
data,
options: NSJSONReadingOptions.MutableContainers,
error: &serializationError
) as NSDictionary
if let error = serializationError {
println("GooglePlaces Error: \(error.localizedDescription)")
return
}
if let status = json["status"] as? String {
if status != "OK" {
println("GooglePlaces API Error: \(status)")
return
}
}
// Perform table updates on UI thread
dispatch_async(dispatch_get_main_queue(), {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
success(json)
})
}
}
| mit | 74555ac8a9cf0054374f101f674f6b71 | 29.555556 | 144 | 0.705455 | 4.853693 | false | false | false | false |
AceWangLei/BYWeiBo | BYWeiBo/BYDiscoverTableViewController.swift | 1 | 3243 | //
// BYDiscoverTableViewController.swift
// BYWeiBo
//
// Created by qingyun on 16/1/26.
// Copyright © 2016年 lit. All rights reserved.
//
import UIKit
class BYDiscoverTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 4d18ac3d2792a5af784a884a95d84e01 | 33.105263 | 157 | 0.687963 | 5.557461 | false | false | false | false |
dnevera/IMProcessing | IMProcessing/Classes/Adjustments/IMPLutFilter.swift | 1 | 2426 | //
// IMPLutFilter.swift
// IMProcessing
//
// Created by denis svinarchuk on 20.12.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
import Foundation
import Metal
public class IMPLutFilter: IMPFilter, IMPAdjustmentProtocol {
public static let defaultAdjustment = IMPAdjustment(blending: IMPBlending(mode: IMPBlendingMode.NORMAL, opacity: 1))
public var adjustment:IMPAdjustment!{
didSet{
self.updateBuffer(&adjustmentBuffer, context:context, adjustment:&adjustment, size:sizeof(IMPAdjustment))
self.dirty = true
}
}
public var adjustmentBuffer:MTLBuffer?
public var kernel:IMPFunction!
internal var lut:IMPImageProvider?
internal var _lutDescription = IMPImageProvider.LutDescription()
public var lutDescription:IMPImageProvider.LutDescription{
return _lutDescription
}
public required init(context: IMPContext, lut:IMPImageProvider, description:IMPImageProvider.LutDescription) {
super.init(context: context)
update(lut, description: description)
defer{
self.adjustment = IMPLutFilter.defaultAdjustment
}
}
public required init(context: IMPContext) {
fatalError("init(context:) has not been implemented, IMPLutFilter(context: IMPContext, lut:IMPImageProvider, description:IMPImageProvider.lutDescription) should be used instead...")
}
public func update(lut:IMPImageProvider, description:IMPImageProvider.LutDescription){
var name = "kernel_adjustLut"
if description.type == .D1D {
name += "D1D"
}
else if description.type == .D3D {
name += "D3D"
}
if self._lutDescription.type != description.type || kernel == nil {
if kernel != nil {
self.removeFunction(kernel)
}
kernel = IMPFunction(context: self.context, name: name)
self.addFunction(kernel)
}
self.lut = lut
self._lutDescription = description
self.dirty = true
}
public override func configure(function: IMPFunction, command: MTLComputeCommandEncoder) {
if kernel == function {
command.setTexture(lut?.texture, atIndex: 2)
command.setBuffer(adjustmentBuffer, offset: 0, atIndex: 0)
}
}
}
| mit | 0991c73879818dca45d848563d87b035 | 31.333333 | 189 | 0.638351 | 4.681467 | false | false | false | false |
dnevera/IMProcessing | IMPTests/IMPGeometryTest/IMPGeometryTest/IMPDocument.swift | 1 | 4093 | //
// IMPDocument.swift
//
// Created by denis svinarchuk on 15.12.15.
// Copyright © 2015 IMetalling. All rights reserved.
//
import Cocoa
import IMProcessing
public enum IMPDocumentType{
case Image
case LUT
}
public typealias IMPDocumentObserver = ((file:String, type:IMPDocumentType) -> Void)
public class IMPDocument: NSObject {
private override init() {}
private var didUpdateDocumnetHandlers = [IMPDocumentObserver]()
static let sharedInstance = IMPDocument()
var currentFile:String?{
didSet{
addOpenRecentFileMenuItem(currentFile!)
for o in self.didUpdateDocumnetHandlers{
o(file: currentFile!, type: .Image)
}
}
}
func addDocumentObserver(observer:IMPDocumentObserver){
didUpdateDocumnetHandlers.append(observer)
}
func saveCurrent(filename:String){
if let cf = currentFile{
addOpenRecentFileMenuItem(cf)
}
}
private let openRecentKey = "imageMetalling-open-recent"
private var openRecentMenuItems = Dictionary<String,NSMenuItem>()
public weak var openRecentMenu: NSMenu! {
didSet{
if let list = openRecentList {
if list.count>0{
for file in list.reverse() {
addOpenRecentMenuItemMenu(file)
}
IMPDocument.sharedInstance.currentFile = list[0]
}
}
}
}
public func clearRecent(){
if let list = openRecentList {
for file in list {
removeOpenRecentFileMenuItem(file)
}
}
}
public func openRecentListAdd(urls:[NSURL]){
for url in urls{
if let file = url.path{
self.addOpenRecentFileMenuItem(file)
}
}
}
private func addOpenRecentMenuItemMenu(file:String){
if let menu = openRecentMenu {
let menuItem = menu.insertItemWithTitle(file, action: Selector("openRecentHandler:"), keyEquivalent: "", atIndex: 0)
openRecentMenuItems[file]=menuItem
}
}
private func openFilePath(filePath: String){
currentFile = filePath
}
private var openRecentList:[String]?{
get {
return NSUserDefaults.standardUserDefaults().objectForKey(openRecentKey) as? [String]
}
}
private func addOpenRecentFileMenuItem(file:String){
var list = removeOpenRecentFileMenuItem(file)
list.insert(file, atIndex: 0)
NSUserDefaults.standardUserDefaults().setObject(list, forKey: openRecentKey)
NSUserDefaults.standardUserDefaults().synchronize()
addOpenRecentMenuItemMenu(file)
}
private func removeOpenRecentFileMenuItem(file:String) -> [String] {
var list = openRecentList ?? [String]()
if let index = list.indexOf(file){
list.removeAtIndex(index)
if let menuItem = openRecentMenuItems[file] {
openRecentMenu.removeItem(menuItem)
}
}
NSUserDefaults.standardUserDefaults().setObject(list, forKey: openRecentKey)
NSUserDefaults.standardUserDefaults().synchronize()
return list
}
var currentLutFile:String?{
didSet{
for o in self.didUpdateDocumnetHandlers{
o(file: currentLutFile!, type: .LUT)
}
}
}
public func openFilePanel(types:[String]){
let openPanel = NSOpenPanel()
openPanel.canChooseFiles = true;
openPanel.resolvesAliases = true;
openPanel.extensionHidden = false;
openPanel.allowedFileTypes = ["jpg", "jpeg"]
let result = openPanel.runModal()
if result == NSModalResponseOK {
IMPDocument.sharedInstance.currentFile = openPanel.URLs[0].path
}
}
}
| mit | a59098e67f04eac1c15db20ce1b66459 | 26.648649 | 128 | 0.5826 | 5.342037 | false | false | false | false |
tjw/swift | validation-test/compiler_crashers_2/0123-rdar31164540.swift | 1 | 29683 | // RUN: not --crash %target-swift-frontend -parse-stdlib -DBUILDING_OUTSIDE_STDLIB %s -emit-ir
// REQUIRES: objc_interop
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if BUILDING_OUTSIDE_STDLIB
import Swift
internal func _conditionallyUnreachable() -> Never {
_conditionallyUnreachable()
}
extension Array {
func _getOwner_native() -> Builtin.NativeObject { fatalError() }
}
#endif
@_transparent
internal func _abstract(
methodName: StaticString = #function,
file: StaticString = #file, line: UInt = #line
) -> Never {
#if INTERNAL_CHECKS_ENABLED
_fatalErrorMessage("abstract method", methodName, file: file, line: line,
flags: _fatalErrorFlags())
#else
_conditionallyUnreachable()
#endif
}
// MARK: Type-erased abstract base classes
public class AnyKeyPath: Hashable {
public func appending<Value, AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> AnyKeyPath? {
_abstract()
}
public class var rootType: Any.Type {
_abstract()
}
public class var valueType: Any.Type {
_abstract()
}
final public var hashValue: Int {
var hash = 0
withBuffer {
var buffer = $0
while true {
let (component, type) = buffer.next()
hash ^= _mixInt(component.value.hashValue)
if let type = type {
hash ^= _mixInt(unsafeBitCast(type, to: Int.self))
} else {
break
}
}
}
return hash
}
public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool {
// Fast-path identical objects
if a === b {
return true
}
// Short-circuit differently-typed key paths
if type(of: a) != type(of: b) {
return false
}
return a.withBuffer {
var aBuffer = $0
return b.withBuffer {
var bBuffer = $0
// Two equivalent key paths should have the same reference prefix
if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix {
return false
}
while true {
let (aComponent, aType) = aBuffer.next()
let (bComponent, bType) = bBuffer.next()
if aComponent.header.endOfReferencePrefix
!= bComponent.header.endOfReferencePrefix
|| aComponent.value != bComponent.value
|| aType != bType {
return false
}
if aType == nil {
return true
}
}
}
}
}
// MARK: Implementation details
// Prevent normal initialization. We use tail allocation via
// allocWithTailElems().
internal init() {
_sanityCheckFailure("use _create(...)")
}
public // @testable
static func _create(
capacityInBytes bytes: Int,
initializedBy body: (UnsafeMutableRawBufferPointer) -> Void
) -> Self {
_sanityCheck(bytes > 0 && bytes % 4 == 0,
"capacity must be multiple of 4 bytes")
let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue,
Int32.self)
let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result,
Int32.self))
body(UnsafeMutableRawBufferPointer(start: base, count: bytes))
return result
}
func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T {
defer { _fixLifetime(self) }
let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self))
return try f(KeyPathBuffer(base: base))
}
}
public class PartialKeyPath<Root>: AnyKeyPath {
public override func appending<Value, AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> KeyPath<Root, AppendedValue>? {
_abstract()
}
public func appending<Value, AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>? {
_abstract()
}
// MARK: Override abstract interfaces
@inlinable
public final override class var rootType: Any.Type {
return Root.self
}
}
// MARK: Concrete implementations
// FIXME(ABI): This protocol is a hack to work around the inability to have
// "new" non-overriding overloads in subclasses
public protocol _KeyPath {
associatedtype _Root
associatedtype _Value
}
public class KeyPath<Root, Value>: PartialKeyPath<Root>, _KeyPath {
public typealias _Root = Root
public typealias _Value = Value
public func appending<AppendedValue>(
path: KeyPath<Value, AppendedValue>
) -> KeyPath<Root, AppendedValue> {
let resultTy = type(of: self).appendedType(with: type(of: path))
return withBuffer {
var rootBuffer = $0
return path.withBuffer {
var leafBuffer = $0
// Result buffer has room for both key paths' components, plus the
// header, plus space for the middle key path component.
let resultSize = rootBuffer.data.count + leafBuffer.data.count
+ MemoryLayout<KeyPathBuffer.Header>.size
+ MemoryLayout<Int>.size
return resultTy._create(capacityInBytes: resultSize) {
var destBuffer = $0
func pushRaw(_ count: Int) {
_sanityCheck(destBuffer.count >= count)
destBuffer = UnsafeMutableRawBufferPointer(
start: destBuffer.baseAddress.unsafelyUnwrapped + count,
count: destBuffer.count - count
)
}
func pushType(_ type: Any.Type) {
let intSize = MemoryLayout<Int>.size
_sanityCheck(destBuffer.count >= intSize)
if intSize == 8 {
let words = unsafeBitCast(type, to: (UInt32, UInt32).self)
destBuffer.storeBytes(of: words.0,
as: UInt32.self)
destBuffer.storeBytes(of: words.1, toByteOffset: 4,
as: UInt32.self)
} else if intSize == 4 {
destBuffer.storeBytes(of: type, as: Any.Type.self)
} else {
_sanityCheckFailure("unsupported architecture")
}
pushRaw(intSize)
}
// Save space for the header.
let header = KeyPathBuffer.Header(
size: resultSize - 4,
trivial: rootBuffer.trivial && leafBuffer.trivial,
hasReferencePrefix: rootBuffer.hasReferencePrefix
|| leafBuffer.hasReferencePrefix
)
destBuffer.storeBytes(of: header, as: KeyPathBuffer.Header.self)
pushRaw(MemoryLayout<KeyPathBuffer.Header>.size)
let leafHasReferencePrefix = leafBuffer.hasReferencePrefix
let leafIsReferenceWritable = type(of: path).kind == .reference
// Clone the root components into the buffer.
while true {
let (component, type) = rootBuffer.next()
let isLast = type == nil
// If the leaf appended path has a reference prefix, then the
// entire root is part of the reference prefix.
let endOfReferencePrefix: Bool
if leafHasReferencePrefix {
endOfReferencePrefix = false
} else if isLast && leafIsReferenceWritable {
endOfReferencePrefix = true
} else {
endOfReferencePrefix = component.header.endOfReferencePrefix
}
component.clone(
into: &destBuffer,
endOfReferencePrefix: endOfReferencePrefix
)
if let type = type {
pushType(type)
} else {
// Insert our endpoint type between the root and leaf components.
pushType(Value.self)
break
}
}
// Clone the leaf components into the buffer.
while true {
let (component, type) = rootBuffer.next()
component.clone(
into: &destBuffer,
endOfReferencePrefix: component.header.endOfReferencePrefix
)
if let type = type {
pushType(type)
} else {
break
}
}
_sanityCheck(destBuffer.count == 0,
"did not fill entire result buffer")
}
}
}
}
@inlinable
public final func appending<AppendedValue>(
path: ReferenceWritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue> {
return unsafeDowncast(
appending(path: path as KeyPath<Value, AppendedValue>),
to: ReferenceWritableKeyPath<Root, AppendedValue>.self
)
}
// MARK: Override optional-returning abstract interfaces
@inlinable
public final override func appending<Value2, AppendedValue>(
path: KeyPath<Value2, AppendedValue>
) -> KeyPath<Root, AppendedValue>? {
if Value2.self == Value.self {
return .some(appending(
path: unsafeDowncast(path, to: KeyPath<Value, AppendedValue>.self)))
}
return nil
}
@inlinable
public final override func appending<Value2, AppendedValue>(
path: ReferenceWritableKeyPath<Value2, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue>? {
if Value2.self == Value.self {
return .some(appending(
path: unsafeDowncast(path,
to: ReferenceWritableKeyPath<Value, AppendedValue>.self)))
}
return nil
}
@inlinable
public final override class var valueType: Any.Type {
return Value.self
}
// MARK: Implementation
enum Kind { case readOnly, value, reference }
class var kind: Kind { return .readOnly }
static func appendedType<AppendedValue>(
with t: KeyPath<Value, AppendedValue>.Type
) -> KeyPath<Root, AppendedValue>.Type {
let resultKind: Kind
switch (self.kind, t.kind) {
case (_, .reference):
resultKind = .reference
case (let x, .value):
resultKind = x
default:
resultKind = .readOnly
}
switch resultKind {
case .readOnly:
return KeyPath<Root, AppendedValue>.self
case .value:
return WritableKeyPath.self
case .reference:
return ReferenceWritableKeyPath.self
}
}
final func projectReadOnly(from root: Root) -> Value {
// TODO: For perf, we could use a local growable buffer instead of Any
var curBase: Any = root
return withBuffer {
var buffer = $0
while true {
let (rawComponent, optNextType) = buffer.next()
let valueType = optNextType ?? Value.self
let isLast = optNextType == nil
func project<CurValue>(_ base: CurValue) -> Value? {
func project2<NewValue>(_: NewValue.Type) -> Value? {
let newBase: NewValue = rawComponent.projectReadOnly(base)
if isLast {
_sanityCheck(NewValue.self == Value.self,
"key path does not terminate in correct type")
return unsafeBitCast(newBase, to: Value.self)
} else {
curBase = newBase
return nil
}
}
return _openExistential(valueType, do: project2)
}
if let result = _openExistential(curBase, do: project) {
return result
}
}
}
}
deinit {
withBuffer { $0.destroy() }
}
}
public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> {
public final func appending<AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> WritableKeyPath<Root, AppendedValue> {
return unsafeDowncast(
appending(path: path as KeyPath<Value, AppendedValue>),
to: WritableKeyPath<Root, AppendedValue>.self
)
}
// MARK: Implementation detail
override class var kind: Kind { return .value }
// `base` is assumed to be undergoing a formal access for the duration of the
// call, so must not be mutated by an alias
func projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) {
var p = UnsafeRawPointer(base)
var type: Any.Type = Root.self
var keepAlive: [AnyObject] = []
return withBuffer {
var buffer = $0
_sanityCheck(!buffer.hasReferencePrefix,
"WritableKeyPath should not have a reference prefix")
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent.projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == UnsafeRawPointer(base),
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(type, do: project)
if optNextType == nil { break }
type = nextType
}
// TODO: With coroutines, it would be better to yield here, so that
// we don't need the hack of the keepAlive array to manage closing
// accesses.
let typedPointer = p.assumingMemoryBound(to: Value.self)
return (pointer: UnsafeMutablePointer(mutating: typedPointer),
owner: keepAlive._getOwner_native())
}
}
}
public class ReferenceWritableKeyPath<Root, Value>: WritableKeyPath<Root, Value> {
/* TODO: need a "new" attribute
public final func appending<AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue> {
return unsafeDowncast(
appending(path: path as KeyPath<Value, AppendedValue>),
to: ReferenceWritableKeyPath<Root, AppendedValue>.self
)
}*/
// MARK: Implementation detail
final override class var kind: Kind { return .reference }
final override func projectMutableAddress(from base: UnsafePointer<Root>)
-> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) {
// Since we're a ReferenceWritableKeyPath, we know we don't mutate the base in
// practice.
return projectMutableAddress(from: base.pointee)
}
final func projectMutableAddress(from origBase: Root)
-> (pointer: UnsafeMutablePointer<Value>, owner: Builtin.NativeObject) {
var keepAlive: [AnyObject] = []
var address: UnsafeMutablePointer<Value> = withBuffer {
var buffer = $0
// Project out the reference prefix.
var base: Any = origBase
while buffer.hasReferencePrefix {
let (rawComponent, optNextType) = buffer.next()
_sanityCheck(optNextType != nil,
"reference prefix should not go to end of buffer")
let nextType = optNextType.unsafelyUnwrapped
func project<NewValue>(_: NewValue.Type) -> Any {
func project2<CurValue>(_ base: CurValue) -> Any {
return rawComponent.projectReadOnly(base) as NewValue
}
return _openExistential(base, do: project2)
}
base = _openExistential(nextType, do: project)
}
// Start formal access to the mutable value, based on the final base
// value.
func formalMutation<MutationRoot>(_ base: MutationRoot)
-> UnsafeMutablePointer<Value> {
var base2 = base
return withUnsafeBytes(of: &base2) { baseBytes in
var p = baseBytes.baseAddress.unsafelyUnwrapped
var curType: Any.Type = MutationRoot.self
while true {
let (rawComponent, optNextType) = buffer.next()
let nextType = optNextType ?? Value.self
func project<CurValue>(_: CurValue.Type) {
func project2<NewValue>(_: NewValue.Type) {
p = rawComponent.projectMutableAddress(p,
from: CurValue.self,
to: NewValue.self,
isRoot: p == baseBytes.baseAddress,
keepAlive: &keepAlive)
}
_openExistential(nextType, do: project2)
}
_openExistential(curType, do: project)
if optNextType == nil { break }
curType = nextType
}
let typedPointer = p.assumingMemoryBound(to: Value.self)
return UnsafeMutablePointer(mutating: typedPointer)
}
}
return _openExistential(base, do: formalMutation)
}
return (address, keepAlive._getOwner_native())
}
}
extension _KeyPath where Self: ReferenceWritableKeyPath<_Root, _Value> {
@inlinable
public final func appending<AppendedValue>(
path: WritableKeyPath<Value, AppendedValue>
) -> ReferenceWritableKeyPath<Root, AppendedValue> {
return unsafeDowncast(
appending(path: path as KeyPath<Value, AppendedValue>),
to: ReferenceWritableKeyPath<Root, AppendedValue>.self
)
}
}
// MARK: Implementation details
enum KeyPathComponentKind {
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
}
enum KeyPathComponent: Hashable {
struct RawAccessor {
var rawCode: Builtin.RawPointer
var rawContext: Builtin.NativeObject?
}
/// The keypath projects within the storage of the outer value, like a
/// stored property in a struct.
case `struct`(offset: Int)
/// The keypath projects from the referenced pointer, like a
/// stored property in a class.
case `class`(offset: Int)
/// The keypath optional-chains, returning nil immediately if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalChain
/// The keypath optional-forces, trapping if the input is
/// nil, or else proceeding by projecting the value inside.
case optionalForce
/// The keypath wraps a value in an optional.
case optionalWrap
static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool {
switch (a, b) {
case (.struct(offset: let a), .struct(offset: let b)),
(.class (offset: let a), .class (offset: let b)):
return a == b
case (.optionalChain, .optionalChain),
(.optionalForce, .optionalForce),
(.optionalWrap, .optionalWrap):
return true
case (.struct, _),
(.class, _),
(.optionalChain, _),
(.optionalForce, _),
(.optionalWrap, _):
return false
}
}
var hashValue: Int {
var hash: Int = 0
switch self {
case .struct(offset: let a):
hash ^= _mixInt(0)
hash ^= _mixInt(a)
case .class(offset: let b):
hash ^= _mixInt(1)
hash ^= _mixInt(b)
case .optionalChain:
hash ^= _mixInt(2)
case .optionalForce:
hash ^= _mixInt(3)
case .optionalWrap:
hash ^= _mixInt(4)
}
return hash
}
}
struct RawKeyPathComponent {
var header: Header
var body: UnsafeRawBufferPointer
struct Header {
static var payloadBits: Int { return 29 }
static var payloadMask: Int { return 0xFFFF_FFFF >> (32 - payloadBits) }
var _value: UInt32
var discriminator: Int { return Int(_value) >> Header.payloadBits & 0x3 }
var payload: Int {
get { return Int(_value) & Header.payloadMask }
set {
_sanityCheck(newValue & Header.payloadMask == newValue,
"payload too big")
let shortMask = UInt32(Header.payloadMask)
_value = _value & ~shortMask | UInt32(newValue)
}
}
var endOfReferencePrefix: Bool {
get {
return Int(_value) >> Header.payloadBits & 0x4 != 0
}
set {
let bit = 0x4 << UInt32(Header.payloadBits)
if newValue {
_value = _value | bit
} else {
_value = _value & ~bit
}
}
}
var kind: KeyPathComponentKind {
switch (discriminator, payload) {
case (0, _):
return .struct
case (2, _):
return .class
case (3, 0):
return .optionalChain
case (3, 1):
return .optionalWrap
case (3, 2):
return .optionalForce
default:
_sanityCheckFailure("invalid header")
}
}
var bodySize: Int {
switch kind {
case .struct, .class:
if payload == Header.payloadMask { return 4 } // overflowed
return 0
case .optionalChain, .optionalForce, .optionalWrap:
return 0
}
}
var isTrivial: Bool {
switch kind {
case .struct, .class, .optionalChain, .optionalForce, .optionalWrap:
return true
}
}
}
var _structOrClassOffset: Int {
_sanityCheck(header.kind == .struct || header.kind == .class,
"no offset for this kind")
// An offset too large to fit inline is represented by a signal and stored
// in the body.
if header.payload == Header.payloadMask {
// Offset overflowed into body
_sanityCheck(body.count >= MemoryLayout<UInt32>.size,
"component not big enough")
return Int(body.load(as: UInt32.self))
}
return header.payload
}
var value: KeyPathComponent {
switch header.kind {
case .struct:
return .struct(offset: _structOrClassOffset)
case .class:
return .class(offset: _structOrClassOffset)
case .optionalChain:
return .optionalChain
case .optionalForce:
return .optionalForce
case .optionalWrap:
return .optionalWrap
}
}
func destroy() {
switch header.kind {
case .struct,
.class,
.optionalChain,
.optionalForce,
.optionalWrap:
// trivial
return
}
}
func clone(into buffer: inout UnsafeMutableRawBufferPointer,
endOfReferencePrefix: Bool) {
var newHeader = header
newHeader.endOfReferencePrefix = endOfReferencePrefix
var componentSize = MemoryLayout<Header>.size
buffer.storeBytes(of: newHeader, as: Header.self)
switch header.kind {
case .struct,
.class:
if header.payload == Header.payloadMask {
let overflowOffset = body.load(as: UInt32.self)
buffer.storeBytes(of: overflowOffset, toByteOffset: 4,
as: UInt32.self)
componentSize += 4
}
case .optionalChain,
.optionalForce,
.optionalWrap:
break
}
_sanityCheck(buffer.count >= componentSize)
buffer = UnsafeMutableRawBufferPointer(
start: buffer.baseAddress.unsafelyUnwrapped + componentSize,
count: buffer.count - componentSize
)
}
func projectReadOnly<CurValue, NewValue>(_ base: CurValue) -> NewValue {
switch value {
case .struct(let offset):
var base2 = base
return withUnsafeBytes(of: &base2) {
let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset)
// The contents of the struct should be well-typed, so we can assume
// typed memory here.
return p.assumingMemoryBound(to: NewValue.self).pointee
}
case .class(let offset):
_sanityCheck(CurValue.self is AnyObject.Type,
"base is not a class")
let baseObj = unsafeBitCast(base, to: AnyObject.self)
let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj))
defer { _fixLifetime(baseObj) }
return basePtr.advanced(by: offset)
.assumingMemoryBound(to: NewValue.self)
.pointee
case .optionalChain:
fatalError("TODO")
case .optionalForce:
fatalError("TODO")
case .optionalWrap:
fatalError("TODO")
}
}
func projectMutableAddress<CurValue, NewValue>(
_ base: UnsafeRawPointer,
from _: CurValue.Type,
to _: NewValue.Type,
isRoot: Bool,
keepAlive: inout [AnyObject]
) -> UnsafeRawPointer {
switch value {
case .struct(let offset):
return base.advanced(by: offset)
case .class(let offset):
// A class dereference should only occur at the root of a mutation,
// since otherwise it would be part of the reference prefix.
_sanityCheck(isRoot,
"class component should not appear in the middle of mutation")
// AnyObject memory can alias any class reference memory, so we can
// assume type here
let object = base.assumingMemoryBound(to: AnyObject.self).pointee
// The base ought to be kept alive for the duration of the derived access
keepAlive.append(object)
return UnsafeRawPointer(Builtin.bridgeToRawPointer(object))
.advanced(by: offset)
case .optionalForce:
fatalError("TODO")
case .optionalChain, .optionalWrap:
_sanityCheckFailure("not a mutable key path component")
}
}
}
internal struct KeyPathBuffer {
var data: UnsafeRawBufferPointer
var trivial: Bool
var hasReferencePrefix: Bool
struct Header {
var _value: UInt32
init(size: Int, trivial: Bool, hasReferencePrefix: Bool) {
_sanityCheck(size <= 0x3FFF_FFFF, "key path too big")
_value = UInt32(size)
| (trivial ? 0x8000_0000 : 0)
| (hasReferencePrefix ? 0x4000_0000 : 0)
}
var size: Int { return Int(_value & 0x3FFF_FFFF) }
var trivial: Bool { return _value & 0x8000_0000 != 0 }
var hasReferencePrefix: Bool { return _value & 0x4000_0000 != 0 }
}
init(base: UnsafeRawPointer) {
let header = base.load(as: Header.self)
data = UnsafeRawBufferPointer(
start: base + MemoryLayout<Header>.size,
count: header.size
)
trivial = header.trivial
hasReferencePrefix = header.hasReferencePrefix
}
func destroy() {
if trivial { return }
fatalError("TODO")
}
mutating func next() -> (RawKeyPathComponent, Any.Type?) {
let header = pop(RawKeyPathComponent.Header.self)
// Track if this is the last component of the reference prefix.
if header.endOfReferencePrefix {
_sanityCheck(self.hasReferencePrefix,
"beginMutation marker in non-reference-writable key path?")
self.hasReferencePrefix = false
}
let body: UnsafeRawBufferPointer
let size = header.bodySize
if size != 0 {
body = popRaw(size)
} else {
body = UnsafeRawBufferPointer(start: nil, count: 0)
}
let component = RawKeyPathComponent(header: header, body: body)
// fetch type, which is in the buffer unless it's the final component
let nextType: Any.Type?
if data.count == 0 {
nextType = nil
} else {
if MemoryLayout<Any.Type>.size == 8 {
// Words in the key path buffer are 32-bit aligned
nextType = unsafeBitCast(pop((Int32, Int32).self),
to: Any.Type.self)
} else if MemoryLayout<Any.Type>.size == 4 {
nextType = pop(Any.Type.self)
} else {
_sanityCheckFailure("unexpected word size")
}
}
return (component, nextType)
}
mutating func pop<T>(_ type: T.Type) -> T {
let raw = popRaw(MemoryLayout<T>.size)
return raw.load(as: type)
}
mutating func popRaw(_ size: Int) -> UnsafeRawBufferPointer {
_sanityCheck(data.count >= size,
"not enough space for next component?")
let result = UnsafeRawBufferPointer(start: data.baseAddress, count: size)
data = UnsafeRawBufferPointer(
start: data.baseAddress.unsafelyUnwrapped + size,
count: data.count - size
)
return result
}
}
public struct _KeyPathBase<T> {
public var base: T
public init(base: T) { self.base = base }
// TODO: These subscripts ought to sit on `Any`
public subscript<U>(keyPath: KeyPath<T, U>) -> U {
return keyPath.projectReadOnly(from: base)
}
public subscript<U>(keyPath: WritableKeyPath<T, U>) -> U {
get {
return keyPath.projectReadOnly(from: base)
}
mutableAddressWithNativeOwner {
// The soundness of this `addressof` operation relies on the returned
// address from an address only being used during a single formal access
// of `self` (IOW, there's no end of the formal access between
// `materializeForSet` and its continuation).
let basePtr = UnsafeMutablePointer<T>(Builtin.addressof(&base))
return keyPath.projectMutableAddress(from: basePtr)
}
}
public subscript<U>(keyPath: ReferenceWritableKeyPath<T, U>) -> U {
get {
return keyPath.projectReadOnly(from: base)
}
nonmutating mutableAddressWithNativeOwner {
return keyPath.projectMutableAddress(from: base)
}
}
}
| apache-2.0 | 6e108b3ec4d62f5e86a55e434cbf4836 | 30.917204 | 94 | 0.610551 | 4.743209 | false | false | false | false |
zerdzhong/LeetCode | swift/LeetCode.playground/Pages/12_Integer_to_Roman.xcplaygroundpage/Contents.swift | 1 | 594 | //: [Previous](@previous)
//https://leetcode.com/problems/integer-to-roman/
import Foundation
class Solution {
func intToRoman(_ num: Int) -> String {
let I = ["","I","II","III","IV","V","VI","VII","VIII","IX"]
let X = ["", "X","XX","XXX","XL","L","LX","LXX","LXXX","XC"]
let C = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"]
let M = ["", "M", "MM", "MMM"]
return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}
}
let testInt = 1301
Solution().intToRoman(testInt)
//: [Next](@next)
| mit | 8ac5ff4513c914334abbf97012dbc808 | 24.826087 | 77 | 0.468013 | 2.883495 | false | true | false | false |
barbosa/clappr-ios | Pod/Classes/Plugin/Container/LoadingContainerPlugin.swift | 1 | 2274 | public class LoadingContainerPlugin: UIContainerPlugin {
private var spinningWheel: UIActivityIndicatorView
public required init() {
spinningWheel = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
super.init()
addSubview(spinningWheel)
userInteractionEnabled = false
}
public override var pluginName: String {
return "spinner"
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func render() {
addCenteringConstraints()
bindEventListeners()
}
private func addCenteringConstraints() {
translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: self, attribute: .Width, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: spinningWheel.frame.width)
addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: self, attribute: .Height, relatedBy: .Equal,
toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: spinningWheel.frame.height)
addConstraint(heightConstraint)
let xCenterConstraint = NSLayoutConstraint(item: self, attribute: .CenterX,
relatedBy: .Equal, toItem: container!, attribute: .CenterX, multiplier: 1, constant: 0)
container!.addConstraint(xCenterConstraint)
let yCenterConstraint = NSLayoutConstraint(item: self, attribute: .CenterY,
relatedBy: .Equal, toItem: container!, attribute: .CenterY, multiplier: 1, constant: 0)
container!.addConstraint(yCenterConstraint)
}
private func bindEventListeners() {
listenTo(container!, eventName: ContainerEvent.Buffering.rawValue) {[weak self] _ in
self?.spinningWheel.startAnimating()
}
listenTo(container!, eventName: ContainerEvent.Play.rawValue, callback: stopAnimating)
listenTo(container!, eventName: ContainerEvent.Ended.rawValue, callback: stopAnimating)
}
private func stopAnimating(userInfo: EventUserInfo) {
spinningWheel.stopAnimating()
}
} | bsd-3-clause | 2351a2583360b79f0b5dc1929dee0d80 | 38.912281 | 105 | 0.676781 | 5.532847 | false | false | false | false |
webventil/OpenSport | OpenSport/OpenSport/ActivityLogger.swift | 1 | 8927 | //
// ActivityLogger.swift
// OpenSport
//
// Created by Arne Tempelhof on 25/07/14.
// Copyright (c) 2014 Arne Tempelhof. All rights reserved.
//
import Foundation
import CoreLocation
import UIKit
protocol ActivityLoggerDelegate {
func newTrackpointStored(sportActivity: SportActivity)
func updatedStopwatch(stopwatchTimer: Double)
func updatedDistance(distance: Double)
}
public class ActivityLogger: NSObject, CLLocationManagerDelegate, GeolocatorDelegate {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var delegate: ActivityLoggerDelegate?
var locationManager = CLLocationManager()
var sportActivity: SportActivity?
var backgroundTimer: NSTimer? = nil
var stopwatch: NSTimer? = nil
var currentDistance = 0.0
var isLogging = false
var isPausing = false
var segmentsDuration = 0.0
var trackSegment: TrackSegment?
var isLocating = false
public class func shared() -> ActivityLogger {
struct Static {
static let s_manager = ActivityLogger()
}
return Static.s_manager
}
func applicationDidEnterBackground() {
backgroundTimer = NSTimer.scheduledTimerWithTimeInterval(5, target: self, selector: Selector("restartLocationUpdates"), userInfo: nil, repeats: true)
}
func applicationDidBecomeActive() {
backgroundTimer?.invalidate()
backgroundTimer = nil
}
func restartLocationUpdates() {
locationManager.startUpdatingLocation()
}
public func startLogging() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
locationManager.distanceFilter = 10
locationManager.pausesLocationUpdatesAutomatically = true
locationManager.activityType = .Fitness
sportActivity = DatabaseManager.shared().createActivity()
sportActivity!.startTime = NSDate()
isLogging = true
stopwatch = NSTimer.scheduledTimerWithTimeInterval(1.0 / 10.0, target: self, selector: Selector("updateStopwatch"), userInfo: nil, repeats: true)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("applicationDidEnterBackground"),
name: UIApplicationDidEnterBackgroundNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("applicationDidBecomeActive"),
name: UIApplicationDidBecomeActiveNotification,
object: nil)
VoiceCoach.shared().speak(NSLocalizedString("Starting activity", comment: "voice command for starting activity"))
}
public func setPause(pause: Bool) {
if isPausing == false {
VoiceCoach.shared().speak(NSLocalizedString("Pausing activity", comment: "voice command for starting activity"))
if let firstTrackpoint = trackSegment?.trackpoints.firstObject as? Trackpoint {
segmentsDuration += NSDate().timeIntervalSinceDate(firstTrackpoint.timestamp)
}
trackSegment = nil
} else {
VoiceCoach.shared().speak(NSLocalizedString("Resuming activity", comment: "voice command for starting activity"))
}
isPausing = pause
}
func updateStopwatch() {
if isPausing == false {
if let firstTrackpoint = trackSegment?.trackpoints.firstObject as? Trackpoint {
delegate?.updatedStopwatch(segmentsDuration + NSDate().timeIntervalSinceDate(firstTrackpoint.timestamp))
}
}
}
public func stopLogging() {
locationManager.stopUpdatingLocation()
var userDefaults = NSUserDefaults.standardUserDefaults()
sportActivity!.activityType = userDefaults.objectForKey("activityType") as String
sportActivity!.endTime = NSDate()
sportActivity!.duration = NSDate().timeIntervalSinceDate(sportActivity!.startTime)
sportActivity!.distance = currentDistance
sportActivity = GPXManager.finalizeActivity(sportActivity!)
DatabaseManager.shared().saveContext()
HealthManager.shared().saveWorkoutToHealthKit(currentDistance, startTime: sportActivity!.startTime,
endTime: sportActivity!.endTime, duration: sportActivity!.duration, type: sportActivity!.activityType, kiloCalories: 0.0)
stopwatch?.invalidate()
stopwatch = nil
isLogging = false
NSNotificationCenter.defaultCenter().removeObserver(self)
if let trackpoints = trackSegment?.trackpoints {
if (trackpoints.count > 1) {
println("activity persited")
} else {
println("activity deleted")
DatabaseManager.shared().deleteSportActivity(sportActivity!)
}
} else {
println("activity deleted")
DatabaseManager.shared().deleteSportActivity(sportActivity!)
}
// prevent from logging after stopping
sportActivity = nil
trackSegment = nil
currentDistance = 0
VoiceCoach.shared().speak(NSLocalizedString("Activity completed", comment: "voice command for finish activity"))
}
public func save() {
DatabaseManager.shared().saveContext()
}
public func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if isPausing {
return
}
if manager.location.horizontalAccuracy > 30 {
return
}
if sportActivity?.location == nil {
if isLocating == false {
var geolocator = Geolocator()
geolocator.geolocateByUsingOSM(locationManager.location)
isLocating = true
}
}
var lastLocation = locations[locations.count - 1] as CLLocation
if let trackpoints = trackSegment?.trackpoints.array as? [Trackpoint] {
var previousTrackpoints = trackpoints
if (trackpoints.count > 0) {
var previousTrackpoint = previousTrackpoints.last!
var prevLocation = CLLocation(latitude: previousTrackpoint.latitude.doubleValue, longitude: previousTrackpoint.longitude.doubleValue)
var distance = prevLocation.distanceFromLocation(lastLocation)
// only store point when traveled distance is >= 5m
if distance >= 5 { // TODO this could be a setting
currentDistance += distance
delegate?.updatedDistance(currentDistance)
addLocaction(lastLocation)
}
}
} else {
addLocaction(lastLocation)
}
}
public func locationManagerDidPauseLocationUpdates(manager: CLLocationManager!) {
setPause(true)
}
public func locationManagerDidResumeLocationUpdates(manager: CLLocationManager!) {
setPause(false)
}
func addLocaction(location: CLLocation) {
if isPausing {
return
}
var trackpoint = DatabaseManager.shared().createTrackpoint()
trackpoint.latitude = location.coordinate.latitude
trackpoint.longitude = location.coordinate.longitude
trackpoint.altitude = location.altitude
trackpoint.speed = location.speed
trackpoint.timestamp = location.timestamp
trackpoint.horizontalAccuracy = location.horizontalAccuracy
trackpoint.verticalAccuracy = location.verticalAccuracy
trackpoint.currentDistance = currentDistance
#if ( arch(i386) || arch(x86_64)) && os(iOS)
// TODO due to bug in ATGraphKit generate random values running in simulator
trackpoint.altitude = Int(arc4random_uniform(100))
#endif
if let segment = trackSegment? {
// no need to do anything since tracksegment is already
} else {
trackSegment = DatabaseManager.shared().createSegment()
if let trackSegments = sportActivity?.mutableOrderedSetValueForKey("trackSegments") {
trackSegments.addObject(trackSegment!)
if let moc = sportActivity?.managedObjectContext {
moc.save(nil)
}
}
}
if let trackpoints = trackSegment?.mutableOrderedSetValueForKey("trackpoints") {
trackpoints.addObject(trackpoint)
}
if let sportActivity = self.sportActivity {
self.delegate?.newTrackpointStored(sportActivity)
}
}
// MARK: - GeolocatorDelegate
func geolocater(geolocater: Geolocator, foundLocation: String?) {
if let location = foundLocation {
sportActivity?.location = NSString(string: location)
isLocating = false
}
}
}
| mit | 7bf4884763cd13e3e969ac2caa1d81c5 | 33.600775 | 157 | 0.654531 | 5.49016 | false | false | false | false |
ratreya/lipika-ime | Application/SettingsView.swift | 1 | 5790 | /*
* LipikaApp is companion application for LipikaIME.
* Copyright (C) 2020 Ranganath Atreya
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
import SwiftUI
import LipikaEngine_OSX
struct SettingsView: View {
private var factory = try! LiteratorFactory(config: LipikaConfig())
@ObservedObject var model = SettingsModel()
var body: some View {
VStack {
VStack(alignment: .leading, spacing: 20) {
Spacer(minLength: 5)
VStack(alignment: .leading, spacing: 18) {
HStack {
Text("Use")
MenuButton(model.schemeName) {
ForEach(try! factory.availableSchemes(), id: \.self) { scheme in
Button(scheme) { self.model.schemeName = scheme }
}
}
.padding(0)
.fixedSize()
Text("to transliterate into")
MenuButton(model.scriptName) {
ForEach(model.languages, id: \.self) { script in
Button(script.language) { self.model.scriptName = script.identifier }
}
}
.padding(0)
.fixedSize()
}
VStack(alignment: .center, spacing: 4) {
HStack {
Text("If you type")
TextField("\\", text: $model.stopString)
.textFieldStyle(RoundedBorderTextFieldStyle())
.border(Color.red, width: model.stopCharacterInvalid ? 2 : 0)
.frame(width: 30)
Text("then output what you have so far and process all subsequent inputs afresh")
}
Text("For example, typing ai will output \(model.transliterate("ai")) but typing a\(model.stopString)i will output \(model.stopCharacterExample)").font(.caption)
}
.fixedSize()
HStack {
Text("Any character typed between")
TextField("`", text: $model.escapeString)
.textFieldStyle(RoundedBorderTextFieldStyle())
.border(Color.red, width: model.escapeCharacterInvalid ? 2 : 0)
.frame(width: 30)
Text("will be output as-is in alphanumeric")
}
HStack {
Text("Output logs to the console at")
MenuButton(model.logLevelString) {
ForEach(Logger.Level.allCases, id: \.self) { (level) in
Button(level.rawValue) { self.model.logLevelString = level.rawValue }
}
}
.fixedSize()
.padding(0)
Text("- Debug is most verbose and Fatal is least verbose")
}
}
Divider()
Group {
VStack(alignment: .leading, spacing: 4) {
Toggle(isOn: $model.showCandidates) {
HStack {
Text("Display a pop-up candidates window that shows the")
MenuButton(model.outputInClient ? "Input" : "Output") {
Button("Input") { self.model.outputInClient = true }
Button("Output") { self.model.outputInClient = false }
}
.padding(0)
.scaledToFit()
}
}
Text("Shows\(model.showCandidates ? "\(model.outputInClient ? " input" : " output") in candidate window and" : "") \(model.outputInClient ? "output" : "input") in editor")
.font(.caption)
.padding(.leading, 18)
}
.fixedSize()
VStack(alignment: .leading, spacing: 18) {
Toggle(isOn: $model.globalScriptSelection) {
Text("New Script selection to apply to all applications as opposed to just the one in the foreground")
}
Toggle(isOn: $model.activeSessionOnDelete) {
Text("When you backspace, start a new session with the word being edited")
}.disabled(model.outputInClient)
Toggle(isOn: $model.activeSessionOnInsert) {
Text("When you type inbetween a word, start a new session with the word being edited")
}.disabled(model.outputInClient)
Toggle(isOn: $model.activeSessionOnCursorMove) {
Text("When you move the caret over a word, start a new session with that word")
}.disabled(model.outputInClient)
}
}
}
Spacer(minLength: 38)
PersistenceView(model: model, context: "settings")
Spacer(minLength: 25)
}.padding(20)
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
| gpl-3.0 | 71aa8ed728d8e62b2fbc25f31129ad0f | 48.067797 | 195 | 0.457168 | 5.721344 | false | false | false | false |
chenchangqing/travelMapMvvm | travelMapMvvm/travelMapMvvm/Models/Enums/POILevelEnum.swift | 1 | 1000 | //
// POILevelEnum.swift
// travelMap
//
// Created by green on 15/8/24.
// Copyright (c) 2015年 com.city8. All rights reserved.
//
import Foundation
enum POILevelEnum: String {
case One = "一个星"
case Two = "二个星"
case Three = "三个星"
case Four = "四个星"
case Five = "五个星"
static let allValues = [One,Two,Three,Four,Five]
// 位置
var index : Int {
get {
for var i = 0; i < POILevelEnum.allValues.count; i++ {
if self == POILevelEnum.allValues[i] {
return i
}
}
return -1
}
}
// 查询指定位置的元素
static func instance(index:Int) -> POILevelEnum? {
if index >= 0 && index < POILevelEnum.allValues.count {
return POILevelEnum.allValues[index]
}
return nil
}
} | apache-2.0 | a5f60e75c5f17015e19a4bc777036988 | 19.586957 | 66 | 0.461945 | 3.909091 | false | false | false | false |
furuyan/RadarChartView | Example/RadarChartView/RadarChartViewController2.swift | 1 | 2947 | //
// RadarChartViewController2.swift
// RadarChartView
//
// Created by furuyan on 2017/08/24.
// Copyright (c) 2017 furuyan. All rights reserved.
//
import UIKit
import RadarChartView
class RadarChartViewController2: UITableViewController {
let cellHeight = CGFloat(300)
// flags that has been displayed
var hasBeenDisplayed = [IndexPath: Bool]()
// cell's title
let texts: [String] = ["First", "Second", "Third", "Fourth", "Fifth"]
let dataSets: [[ChartDataSet]] = {
var dataSets = [[ChartDataSet]]()
for i in 0..<5 {
var dataSet = ChartDataSet()
for j in 0..<6 {
let random = arc4random_uniform(100)
dataSet.entries.append(ChartDataEntry(value: CGFloat(random)))
}
dataSets.append([dataSet])
}
return dataSets
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(Cell.self, forCellReuseIdentifier: "Cell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSets.count
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeight
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let labelWidth = CGFloat(60.0)
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! Cell
cell.label.frame = CGRect(x: 0, y: 10, width: labelWidth, height: 20)
cell.label.text = texts[indexPath.row]
cell.chartView.frame = CGRect(x: labelWidth, y: 0, width: view.frame.width - labelWidth, height: cellHeight)
cell.chartView.dataSets = dataSets[indexPath.row]
// Perform animation when each cell is displayed on first time.
if let flag = hasBeenDisplayed[indexPath], flag {
cell.chartView.isAnimationEnabled = false
} else {
hasBeenDisplayed[indexPath] = true
cell.chartView.isAnimationEnabled = true
}
return cell
}
}
class Cell: UITableViewCell {
let label: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = .systemFont(ofSize: 14)
label.textColor = .black
return label
}()
let chartView = RadarChartView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
chartView.titles = ["Apple", "Beef", "Cheese", "Donuts", "Egg", "Fig"]
chartView.webTitles = ["20", "40", "60", "80", "100"]
contentView.addSubview(chartView)
contentView.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 35086f01bb89e40cf72eb2a27415fc4a | 32.488636 | 116 | 0.624024 | 4.655608 | false | false | false | false |
ZoranPandovski/al-go-rithms | data_structures/hash_table/Swift/hash_table.swift | 1 | 2992 | import Foundation
struct HashTable<Key: Hashable, Value> {
private var buckets: [HashNode<Key, Value>?]
private var capacity: Int
private(set) var collisions = 0
private(set) var count = 0
public var isEmpty: Bool { return count == 0 }
init(capacity: Int) {
buckets = [HashNode<Key, Value>?](repeating: nil, count: capacity)
self.capacity = capacity
}
// Adds key value pair to buckets. Updates value if key already exists
mutating func addUpdate(key: Key, value: Value) {
let hashIndex = index(forKey: key)
let destNode = buckets[hashIndex]
if destNode == nil {
count += 1
buckets[hashIndex] = HashNode(key: key, value: value)
} else {
var curNode = destNode
while curNode != nil {
if curNode!.key == key {
collisions += 1
curNode!.value = value
return
}
curNode = curNode!.nextNode
}
count += 1
buckets[hashIndex] = HashNode(key: key, value: value, nextNode: destNode)
}
}
func value(forKey key: Key) -> Value? {
let hashIndex = index(forKey: key)
var node = buckets[hashIndex]
if node == nil {
return nil
}
while node != nil {
if node!.key == key {
return node!.value
}
node = node!.nextNode
}
return nil
}
// Returns the value of the removed element if found, nil otherwise
mutating func remove(atKey key: Key) -> Value? {
let hashIndex = index(forKey: key)
var node = buckets[hashIndex]
if node == nil {
return nil
}
var prevNode: HashNode<Key, Value>?
while node != nil {
if node!.key == key {
if prevNode == nil {
if node!.nextNode == nil {
buckets[hashIndex] = nil
} else {
buckets[hashIndex] = node!.nextNode
}
} else if node!.nextNode == nil {
prevNode!.nextNode = nil
} else {
prevNode!.nextNode = node!.nextNode
}
count -= 1
return node!.value
}
prevNode = node
node = node!.nextNode
}
return nil
}
private func index(forKey key: Key) -> Int {
return abs(key.hashValue) % buckets.count
}
}
class HashNode<Key, Value> {
var key: Key
var value: Value
var nextNode: HashNode?
init(key: Key, value: Value, nextNode: HashNode? = nil) {
self.key = key
self.value = value
self.nextNode = nextNode
}
}
| cc0-1.0 | 7d6d8f1828f900d7d05f0a7ab8f795b9 | 25.954955 | 85 | 0.472928 | 4.833603 | false | false | false | false |
sjf0213/DingShan | DingshanSwift/DingshanSwift/GalleryDetailBottomBar.swift | 1 | 1644 | //
// GalleryDetailBottomBar.swift
// DingshanSwift
//
// Created by song jufeng on 15/11/23.
// Copyright © 2015年 song jufeng. All rights reserved.
//
import Foundation
class GalleryDetailBottomBar : UIView{
var hidePageTip:Bool = false{
didSet{
self.pageIndexLabel?.hidden = hidePageTip
}
}
var title:String = ""{
didSet{
self.titleLabel?.text = title
}
}
var pageText:String = ""{
didSet{
self.pageIndexLabel?.text = pageText
}
}
private var titleLabel:UILabel?
private var pageIndexLabel:UILabel?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame aRect: CGRect) {
super.init(frame: aRect);
self.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.5);
self.titleLabel = UILabel(frame: CGRect(x: 10, y: 0, width: self.frame.size.width - 70, height: self.frame.size.height))
self.titleLabel?.text = "title"
self.titleLabel?.textColor = UIColor.whiteColor()
self.titleLabel?.font = UIFont.systemFontOfSize(15.0)
self.addSubview(self.titleLabel!)
self.pageIndexLabel = UILabel(frame: CGRect(x: self.frame.size.width - 60, y: 0, width: 50, height: self.frame.size.height));
self.pageIndexLabel?.textAlignment = NSTextAlignment.Right
self.pageIndexLabel?.textColor = UIColor.whiteColor()
self.pageIndexLabel?.font = UIFont.systemFontOfSize(15.0)
self.pageIndexLabel?.text = "1/15"
self.addSubview(self.pageIndexLabel!)
}
} | mit | a274613351b94ad9c78ba92ae2181150 | 33.208333 | 133 | 0.638635 | 4.123116 | false | false | false | false |
koher/EasyImagy | Tests/EasyImagyTests/EasyImagyTests.swift | 1 | 8590 | import XCTest
#if canImport(UIKit)
import UIKit
#endif
#if canImport(AppKit)
import AppKit
#endif
import EasyImagy
class EasyImagySample: XCTestCase {
func testSample() {
/**/ #if canImport(UIKit) || canImport(AppKit)
/**/ let x = 0
/**/ let y = 0
/**/ #if canImport(UIKit)
/**/ let imageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
/**/ imageView.image = Image<RGBA<UInt8>>(width: 1, height: 1, pixel: .black).uiImage
/**/ #endif
/**/ if never() {
var image = Image<RGBA<UInt8>>(named: "ImageName")!
/**/ _ = image[0, 0]
/**/ }
/**/ var image = Image<RGBA<UInt8>>(width: 1, height: 1, pixel: .black)
let pixel: RGBA<UInt8> = image[x, y]
image[x, y] = RGBA(red: 255, green: 0, blue: 0, alpha: 127)
image[x, y] = RGBA(0xFF00007F) // red: 255, green: 0, blue: 0, alpha: 127
// Iterates over all pixels
for pixel in image {
// ...
/**/ _ = pixel.description
}
// Image processing (e.g. binarizations)
let binarized: Image<Bool> = image.map { $0.gray >= 127 }
// From/to `UIImage`
/**/ #if canImport(UIKit)
image = Image<RGBA<UInt8>>(uiImage: imageView.image!)
imageView.image = image.uiImage
/**/ #endif
/**/ _ = pixel
/**/ _ = binarized[0, 0]
/**/ #endif
}
func testIntroduction() {
do {
/**/ if never() {
var image: Image<UInt8> = Image(width: 640, height: 480, pixels: [255, 248, /* ... */])
/**/ image[0, 0] = 0
/**/ }
/**/ var image: Image<UInt8> = Image(width: 1, height: 1, pixel: 0)
/**/ let x = 0
/**/ let y = 0
let pixel: UInt8 = image[x, y]
image[x, y] = 255
/**/ _ = pixel
let width: Int = image.width // 640
let height: Int = image.height // 480
/**/ _ = width
/**/ _ = height
}
do {
/**/ #if canImport(UIKit) || canImport(AppKit)
/**/ if never() {
var image = Image<RGBA<UInt8>>(named: "ImageName")!
/**/ image[0, 0] = RGBA(0xffffffff)
/**/ }
/**/ #endif
/**/ let image = Image<RGBA<UInt8>>(width: 10, height: 10, pixel: .black)
let grayscale: Image<UInt8> = image.map { $0.gray }
/**/ _ = grayscale[0, 0]
}
do {
/**/ let image = Image<RGBA<UInt8>>(width: 1, height: 1, pixel: .black)
/**/ let x = 0, y = 0
var another = image // Not copied here because of copy-on-write
another[x, y] = RGBA(0xff0000ff) // Copied here lazily
}
}
func testInitialization() {
#if canImport(UIKit)
do {
/**/ if never() {
let image = Image<RGBA<UInt8>>(named: "ImageName")!
/**/ _ = image.count
/**/ }
}
do {
/**/ if never() {
let image = Image<RGBA<UInt8>>(contentsOfFile: "path/to/file")!
/**/ _ = image.count
/**/ }
}
do {
/**/ if never() {
let image = Image<RGBA<UInt8>>(data: Data(/* ... */))!
/**/ _ = image.count
/**/ }
}
do {
/**/ let imageView: UIImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
/**/ imageView.image = Image<RGBA<UInt8>>(width: 1, height: 1, pixel: RGBA.black).uiImage
let image = Image<RGBA<UInt8>>(uiImage: imageView.image!) // from a UIImage
/**/ _ = image.count
}
#endif
do {
let image = Image<RGBA<UInt8>>(width: 640, height: 480, pixel: .black) // a black RGBA image
/**/ _ = image.count
}
do {
let image = Image<UInt8>(width: 640, height: 480, pixel: .min) // a black grayscale image
/**/ _ = image.count
}
do {
let image = Image<Bool>(width: 640, height: 480, pixel: false) // a black binary image
/**/ _ = image.count
}
do {
/**/ let pixels = [RGBA<UInt8>](repeating: .black, count: 640 * 480)
let image = Image<RGBA<UInt8>>(width: 640, height: 480, pixels: pixels) // from pixels
/**/ _ = image.count
}
}
func testAccessToAPixel() {
/**/ let x = 0
/**/ let y = 0
/**/ var image = Image<RGBA<UInt8>>(width: 1, height: 1, pixel: .red)
do {
// Gets a pixel by subscripts
let pixel = image[x, y]
/**/ _ = pixel
}
/////////////////////////////////
// Sets a pixel by subscripts
image[x, y] = RGBA(0xFF0000FF)
image[x, y].alpha = 127
/////////////////////////////////
// Safe get for a pixel
if let pixel = image.pixelAt(x: x, y: y) {
print(pixel.red)
print(pixel.green)
print(pixel.blue)
print(pixel.alpha)
print(pixel.gray) // (red + green + blue) / 3
print(pixel) // formatted like "#FF0000FF"
} else {
// `pixel` is safe: `nil` is returned when out of bounds
print("Out of bounds")
}
}
func testRotation() {
do {
/**/ let image = Image<UInt8>(width: 1, height: 1, pixel: 0)
let result = image.rotated(by: .pi) // Rotated clockwise by π
/**/ _ = result.count
}
do {
/**/ let image = Image<UInt8>(width: 1, height: 1, pixel: 0)
let result = image.rotated(byDegrees: 180) // Rotated clockwise by 180 degrees
/**/ _ = result.count
}
do {
/**/ let image = Image<RGBA<UInt8>>(width: 1, height: 1, pixel: .red)
// Rotated clockwise by π / 4 and fill the background with red
let result = image.rotated(by: .pi / 4, extrapolatedBy: .constant(.red))
/**/ _ = result.count
}
}
func testResizing() {
do {
/**/ let image = Image<UInt8>(width: 1, height: 1, pixel: 0)
let result = image.resizedTo(width: 320, height: 240)
/**/ _ = result.count
}
do {
/**/ let image = Image<UInt8>(width: 1, height: 1, pixel: 0)
let result = image.resizedTo(width: 320, height: 240, interpolatedBy: .nearestNeighbor)
/**/ _ = result.count
}
}
func testCropping() {
/**/ let image = Image<RGBA<UInt8>>(width: 128, height: 128, pixel: .red)
let slice: ImageSlice<RGBA<UInt8>> = image[32..<64, 32..<64] // No copying costs
let cropped = Image<RGBA<UInt8>>(slice) // Copying is executed here
/**/ _ = cropped.count
}
func testWithUIImage() {
#if canImport(UIKit)
/**/ if never() {
/**/ let imageView = UIImageView()
// From `UIImage`
let image = Image<RGBA<UInt8>>(uiImage: imageView.image!)
// To `UIImage`
imageView.image = image.uiImage
/**/ }
#endif
}
func testWithNSImage() {
#if canImport(AppKit)
/**/ if never() {
/**/ let imageView = NSImageView()
// From `NSImage`
let image = Image<RGBA<UInt8>>(nsImage: imageView.image!)
// To `NSImage`
imageView.image = image.nsImage
/**/ }
#endif
}
func testWithCoreGraphics() {
#if canImport(UIKit)
/**/ if never() {
/**/ let imageView = UIImageView()
// Drawing on images with CoreGraphics
var image = Image<PremultipliedRGBA<UInt8>>(uiImage: imageView.image!)
image.withCGContext { context in
context.setLineWidth(1)
context.setStrokeColor(UIColor.red.cgColor)
context.move(to: CGPoint(x: -1, y: -1))
context.addLine(to: CGPoint(x: 640, y: 480))
context.strokePath()
}
imageView.image = image.uiImage
/**/ }
#endif
}
}
private func never() -> Bool {
return false
}
| mit | dfab590b0c3269a6152ace46778d19ee | 32.030769 | 109 | 0.460061 | 4.001864 | false | false | false | false |
nicolaschriste/MoreFoundation | MoreFoundation/Container.swift | 1 | 5267 | /// Copyright (c) 2017-19 Nicolas Christe
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
import Foundation
/// A Service that can be registered in a `Container`
public protocol ContainerService: AnyObject {
/// Type of the service
associatedtype ServiceClass = Self
/// service descriptor
static var descriptor: Container.ServiceDescriptor<ServiceClass> { get }
}
/// A simple dependency Container.
public class Container {
/// Service unique identifier type
typealias ServiceUid = ObjectIdentifier
/// Service descriptor
/// - parameter Service: service type
public class ServiceDescriptor<Service> {
/// Service uid
fileprivate private(set) var serviceUid: ServiceUid!
/// Constructor
public init() {
serviceUid = ServiceUid(self)
}
}
/// A reference on a service or a service factory
private enum ServiceRef {
/// Ref on a service instance
case instance(AnyObject)
/// Ref on a service factory
case factory((Container) -> AnyObject)
/// Transitive state: service is currently instantiated. Used for dependency loop detection
case instantiating
}
/// Map of registered services
private var services = [ServiceUid: ServiceRef]()
/// Queue in with services are instanced
private let queue: DispatchQueue
/// Queue identifier
private let dispatchSpecificKey = DispatchSpecificKey<ObjectIdentifier>()
/// Constructor
public init(queue: DispatchQueue = DispatchQueue(label: "Container")) {
self.queue = queue
queue.setSpecific(key: dispatchSpecificKey, value: ObjectIdentifier(self))
}
deinit {
queue.setSpecific(key: dispatchSpecificKey, value: nil)
}
/// Register a service
///
/// - Parameters:
/// - factory: factory to create the service
/// - container: self
/// - service: service to register
public func register<S: ContainerService>(factory: @escaping (_ container: Container) -> S) {
guard services[S.descriptor.serviceUid] == nil else {
fatal("Service Already registered")
}
services[S.descriptor.serviceUid] = .factory(factory)
}
/// Get a service. Service is instantiated if required.
///
/// - Parameter descriptor: descriptor of the service to get
/// - Returns: Service instance if found
public func getService<S>(descriptor: ServiceDescriptor<S>) -> S {
if DispatchQueue.getSpecific(key: dispatchSpecificKey) == ObjectIdentifier(self) {
return queue.sync {
self.getServiceLocked(descriptor: descriptor)
}
} else {
return getServiceLocked(descriptor: descriptor)
}
}
/// Get a service. Service is instantiated if required. Run in the container queue.
///
/// - Parameter descriptor: descriptor of the service to get
/// - Returns: Service instance if found
private func getServiceLocked<S>(descriptor: ServiceDescriptor<S>) -> S {
if let serviceRef = services[descriptor.serviceUid] {
switch serviceRef {
case .instance(let service):
// swiftlint:disable:next force_cast
return service as! S
case .factory(let factory):
return create(descriptor: descriptor, factory: factory)
case .instantiating:
fatal("Container dependency loop")
}
}
fatal("Container service \(descriptor) not found")
}
/// Instantiate a service
///
/// - Parameters:
/// - descriptor: descriptor of the service to create
/// - factory: service factory closure
/// - container: self
/// - Returns: created service service
private func create<S>(descriptor: ServiceDescriptor<S>, factory: (_ container: Container) -> AnyObject) -> S {
services[descriptor.serviceUid] = .instantiating
if let service = factory(self) as? S {
services[descriptor.serviceUid] = .instance(service as AnyObject)
return service
}
fatal("Container service \(descriptor) invalid type")
}
}
| mit | a20e36bb6eaa5116dc89b2f5b71fb6bf | 38.014815 | 115 | 0.659768 | 4.964185 | false | false | false | false |
natecook1000/swift | tools/SourceKit/tools/swift-lang/SwiftLang.swift | 5 | 3097 | //===--------------------- SwiftLang.swift -------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This file provides Swift language support by invoking SourceKit internally.
//===----------------------------------------------------------------------===//
enum SourceKitdError: Error, CustomStringConvertible {
case EditorOpenError(message: String)
case EditorCloseError(message: String)
var description: String {
switch self {
case .EditorOpenError(let message):
return "cannot open document: \(message)"
case .EditorCloseError(let message):
return "cannot close document: \(message)"
}
}
}
public class SwiftLang {
fileprivate static func parse(content: String, name: String, isURL: Bool) throws -> String {
let Service = SourceKitdService()
let Request = SourceKitdRequest(uid: .request_EditorOpen)
if isURL {
Request.addParameter(.key_SourceFile, value: content)
} else {
Request.addParameter(.key_SourceText, value: content)
}
Request.addParameter(.key_Name, value: name)
Request.addParameter(.key_SyntaxTreeTransferMode,
value: .kind_SyntaxTreeFull)
Request.addParameter(.key_EnableSyntaxMap, value: 0)
Request.addParameter(.key_EnableStructure, value: 0)
Request.addParameter(.key_SyntacticOnly, value: 1)
// FIXME: SourceKitd error handling.
let Resp = Service.sendSyn(request: Request)
if Resp.isError {
throw SourceKitdError.EditorOpenError(message: Resp.description)
}
let CloseReq = SourceKitdRequest(uid: .request_EditorClose)
CloseReq.addParameter(.key_Name, value: name)
let CloseResp = Service.sendSyn(request: CloseReq)
if CloseResp.isError {
throw SourceKitdError.EditorCloseError(message: CloseResp.description)
}
return Resp.value.getString(.key_SerializedSyntaxTree)
}
/// Parses the Swift file at the provided URL into a `Syntax` tree in Json
/// serialization format by querying SourceKitd service. This function isn't
/// thread safe.
/// - Parameter url: The URL you wish to parse.
/// - Returns: The syntax tree in Json format string.
public static func parse(path: String) throws -> String {
return try parse(content: path, name: path, isURL: true)
}
/// Parses a given source buffer into a `Syntax` tree in Json serialization
/// format by querying SourceKitd service. This function isn't thread safe.
/// - Parameter source: The source buffer you wish to parse.
/// - Returns: The syntax tree in Json format string.
public static func parse(source: String) throws -> String {
return try parse(content: source, name: "foo", isURL: false)
}
}
| apache-2.0 | fdd23aa3a60eb6a94c4a8d720b1f33d5 | 39.220779 | 94 | 0.664514 | 4.411681 | false | false | false | false |
ffried/FFFoundation | Sources/FFFoundation/Containers/Synchronized.swift | 1 | 6583 | //
// Synchronized.swift
// FFFoundation
//
// Created by Florian Friedrich on 09.10.17.
// Copyright 2017 Florian Friedrich
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Dispatch
@propertyWrapper
public final class Synchronized<Guarded>: @unchecked Sendable {
private var _wrappedValue: Guarded
private let queue: DispatchQueue
public var wrappedValue: Guarded {
dispatchPrecondition(condition: .notOnQueue(queue))
return queue.sync { _wrappedValue }
}
public init(value: Guarded, qos: DispatchQoS) {
_wrappedValue = value
queue = DispatchQueue(label: "net.ffried.containers.synchronized<\(String(describing: Guarded.self).lowercased())>.queue", qos: qos)
}
public convenience init(wrappedValue: Guarded) {
self.init(value: wrappedValue, qos: .default)
}
public subscript<T>(keyPath: KeyPath<Guarded, T>) -> T {
dispatchPrecondition(condition: .notOnQueue(queue))
return queue.sync { _wrappedValue[keyPath: keyPath] }
}
@inline(__always)
private func withMutableValue<T>(do work: (inout Guarded) throws -> T) rethrows -> T {
dispatchPrecondition(condition: .onQueue(queue))
return try work(&_wrappedValue)
}
public func withValue<T>(do work: (inout Guarded) throws -> T) rethrows -> T {
dispatchPrecondition(condition: .notOnQueue(queue))
return try queue.sync { try withMutableValue(do: work) }
}
@inlinable
public func withValueVoid(do work: (inout Guarded) throws -> Void) rethrows {
try withValue(do: work)
}
public func coordinated(with other: Synchronized) -> (Guarded, Guarded) {
dispatchPrecondition(condition: .notOnQueue(queue))
return queue.sync { (_wrappedValue, queue === other.queue ? other._wrappedValue : other.wrappedValue) }
}
public func coordinated<OtherGuarded>(with other: Synchronized<OtherGuarded>) -> (Guarded, OtherGuarded) {
dispatchPrecondition(condition: .notOnQueue(queue))
return queue.sync { (_wrappedValue, other.wrappedValue) }
}
public func combined(with other: Synchronized) -> Synchronized<(Guarded, Guarded)> {
Synchronized<(Guarded, Guarded)>(value: coordinated(with: other), qos: max(queue.qos, other.queue.qos))
}
public func combined<OtherGuarded>(with other: Synchronized<OtherGuarded>) -> Synchronized<(Guarded, OtherGuarded)> {
Synchronized<(Guarded, OtherGuarded)>(value: coordinated(with: other), qos: max(queue.qos, other.queue.qos))
}
@discardableResult
@inlinable
public func exchange(with newValue: Guarded) -> Guarded {
withValue { curVal in
defer { curVal = newValue }
return curVal
}
}
}
// MARK: - Property Wrapper
extension Synchronized where Guarded: ExpressibleByNilLiteral {
@inlinable
public convenience init() { self.init(wrappedValue: nil) }
}
// MARK: - Conditional Conformances
extension Synchronized: Equatable where Guarded: Equatable {
public static func ==(lhs: Synchronized, rhs: Synchronized) -> Bool {
let coordinated = lhs.coordinated(with: rhs)
return coordinated.0 == coordinated.1
}
}
extension Synchronized: Hashable where Guarded: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
extension Synchronized: Comparable where Guarded: Comparable {
public static func <(lhs: Synchronized, rhs: Synchronized) -> Bool {
let coordinated = lhs.coordinated(with: rhs)
return coordinated.0 < coordinated.1
}
}
extension Synchronized: Encodable where Guarded: Encodable {
public func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
}
extension Synchronized: Decodable where Guarded: Decodable {
public convenience init(from decoder: Decoder) throws {
try self.init(wrappedValue: Guarded(from: decoder))
}
}
extension Synchronized: ExpressibleByNilLiteral where Guarded: ExpressibleByNilLiteral {
public convenience init(nilLiteral: ()) {
self.init(wrappedValue: Guarded(nilLiteral: nilLiteral))
}
}
extension Synchronized: ExpressibleByBooleanLiteral where Guarded: ExpressibleByBooleanLiteral {
public convenience init(booleanLiteral value: Guarded.BooleanLiteralType) {
self.init(wrappedValue: Guarded(booleanLiteral: value))
}
}
extension Synchronized: ExpressibleByIntegerLiteral where Guarded: ExpressibleByIntegerLiteral {
public convenience init(integerLiteral value: Guarded.IntegerLiteralType) {
self.init(wrappedValue: Guarded(integerLiteral: value))
}
}
extension Synchronized: ExpressibleByFloatLiteral where Guarded: ExpressibleByFloatLiteral {
public convenience init(floatLiteral value: Guarded.FloatLiteralType) {
self.init(wrappedValue: Guarded(floatLiteral: value))
}
}
extension Synchronized: ExpressibleByUnicodeScalarLiteral where Guarded: ExpressibleByUnicodeScalarLiteral {
public convenience init(unicodeScalarLiteral value: Guarded.UnicodeScalarLiteralType) {
self.init(wrappedValue: Guarded(unicodeScalarLiteral: value))
}
}
extension Synchronized: ExpressibleByExtendedGraphemeClusterLiteral where Guarded: ExpressibleByExtendedGraphemeClusterLiteral {
public convenience init(extendedGraphemeClusterLiteral value: Guarded.ExtendedGraphemeClusterLiteralType) {
self.init(wrappedValue: Guarded(extendedGraphemeClusterLiteral: value))
}
}
extension Synchronized: ExpressibleByStringLiteral where Guarded: ExpressibleByStringLiteral {
public convenience init(stringLiteral value: Guarded.StringLiteralType) {
self.init(wrappedValue: Guarded(stringLiteral: value))
}
}
extension Synchronized: ExpressibleByStringInterpolation where Guarded: ExpressibleByStringInterpolation {
public convenience init(stringInterpolation: Guarded.StringInterpolation) {
self.init(wrappedValue: Guarded(stringInterpolation: stringInterpolation))
}
}
| apache-2.0 | d20e690f7bbc6119ab8a5d74d003eb78 | 36.403409 | 140 | 0.725201 | 4.718996 | false | false | false | false |
superk589/DereGuide | DereGuide/Toolbox/Gacha/Model/CGSSGacha.swift | 2 | 11295 | //
// CGSSGacha.swift
// DereGuide
//
// Created by zzk on 2016/9/13.
// Copyright © 2016 zzk. All rights reserved.
//
import Foundation
import SwiftyJSON
import DynamicColor
extension Array {
func random() -> Element? {
if count >= 0 {
let rand = arc4random_uniform(UInt32(self.count))
return self[Int(rand)]
} else {
return nil
}
}
}
extension CGSSGacha {
var hasOdds: Bool {
return id > 30075
}
var hasLocalRates: Bool {
return id < 30180
}
var hasCachedRates: Bool {
return cachedOdds != nil
}
var cardList: [CGSSCard] {
get {
var list = [CGSSCard]()
let dao = CGSSDAO.shared
for reward in self.rewardTable.values {
if let card = dao.findCardById(reward.cardId) {
list.append(card)
}
}
return list
}
}
var bannerId: Int {
var result = id - 30000
if dicription.contains("クールタイプ") || dicription.contains("パッションタイプ") || dicription.contains("キュートタイプ") {
result = 29
} else if id == 30001 {
// TODO: 初始卡池的图不存在 需要一个placeholder
} else if id == 30013 {
result = 12
}
return result
}
var detailBannerId: Int {
var result = id - 30000
if [30032, 30033, 30034].contains(id) {
result -= 3
}
if dicription.contains("クールタイプ") {
result -= 1
} else if dicription.contains("パッションタイプ") {
result -= 2
} else if id == 30013 {
result = 12
} else if gachaType == .premium {
result = (id % 10000 - 1) / 3 + 1
}
return result
}
var bannerURL: URL! {
return URL(string: String(format: "https://game.starlight-stage.jp/image/announce/title/thumbnail_gacha_%04d.png", bannerId))
}
var detailBannerURL: URL! {
if id > 30170 && isReappeared {
return URL(string: String(format: "https://apis.game.starlight-stage.jp/image/announce/image/header_gacha_%04d.png", detailBannerId))
} else if gachaType == .premium {
return URL(string: String(format: "https://apis.game.starlight-stage.jp/image/announce/header/header_premium_%04d.png", detailBannerId % 10000))
} else {
return URL(string: String(format: "https://apis.game.starlight-stage.jp/image/announce/header/header_gacha_%04d.png", detailBannerId))
}
}
var isReappeared: Bool {
return name.contains("復刻")
}
var gachaType: CGSSGachaTypes {
if dicription.contains("フェス限定") {
return .fes
} else if dicription.contains("期間限定") {
if isReappeared {
return .limitReappear
} else {
return .limit
}
} else if dicription.contains("クールタイプ") || dicription.contains("パッションタイプ") || dicription.contains("キュートタイプ") {
return .singleType
} else if id >= 60000 && id < 70000 {
return .premium
} else {
return .normal
}
}
var gachaColor: UIColor {
switch gachaType {
case .normal:
return .normal
case .limit:
return .limited
case .limitReappear:
return UIColor.limited.lighter()
case .fes:
return .cinfes
case .premium:
return .premium
default:
return .allType
}
}
}
struct Reward {
var cardId: Int
var recommandOrder: Int
var relativeOdds: Int
var relativeSROdds: Int
}
struct CardWithOdds {
var card: CGSSCard
var odds: Int?
}
class CGSSGacha: NSObject {
var dicription: String
var endDate: String
@objc dynamic var id: Int
var name: String
/// 8850 -> 88.5%
var rareRatio: Int
var srRatio: Int
var ssrRatio: Int
@objc dynamic var startDate: String
var rewardTable = [Int: Reward]()
var sr = [Reward]()
var ssr = [Reward]()
var r = [Reward]()
var new = [Reward]()
var newssr = [Reward]()
var newsr = [Reward]()
var newr = [Reward]()
lazy var cachedOdds: GachaOdds? = {
if let odds = GachaOdds(fromCachedDataByGachaID: self.id) {
merge(gachaOdds: odds)
return odds
} else {
return nil
}
}()
lazy var cardsOfguaranteed: [CGSSCard] = {
let semephore = DispatchSemaphore(value: 0)
var result = [CGSSCard]()
CGSSGameResource.shared.master.getGuaranteedCardIds(gacha: self, callback: { (cardIds) in
result.append(contentsOf: cardIds.map { CGSSDAO.shared.findCardById($0) }.compactMap { $0 } )
semephore.signal()
})
semephore.wait()
return result
}()
init(id: Int, name: String, dicription: String, startDate: String, endDate: String, rareRatio: Int, srRatio: Int, ssrRatio: Int, rewards: [Reward]) {
self.id = id
self.name = name
self.dicription = dicription
self.startDate = startDate
self.endDate = endDate
self.rareRatio = rareRatio
self.srRatio = srRatio
self.ssrRatio = ssrRatio
self.rewardTable = [Int: Reward]()
let dao = CGSSDAO.shared
for reward in rewards {
if reward.recommandOrder > 0 {
new.append(reward)
}
self.rewardTable[reward.cardId] = reward
if let card = dao.findCardById(reward.cardId) {
switch card.rarityType {
case CGSSRarityTypes.ssr:
if reward.recommandOrder > 0 {
newssr.append(reward)
} else {
ssr.append(reward)
}
case CGSSRarityTypes.sr:
if reward.recommandOrder > 0 {
newsr.append(reward)
} else {
sr.append(reward)
}
case CGSSRarityTypes.r:
if reward.recommandOrder > 0 {
newr.append(reward)
} else {
r.append(reward)
}
default:
break
}
}
}
}
private struct RewardOdds {
var reward: Reward
/// included
var start: Int
/// not included
var end: Int
}
private var odds: [RewardOdds]!
private var srOdds: [RewardOdds]!
private func generateOdds() {
if odds == nil {
var start = 0
odds = [RewardOdds]()
for reward in rewardTable.values {
odds.append(RewardOdds(reward: reward, start: start, end: start + reward.relativeOdds))
start += reward.relativeOdds
}
}
if srOdds == nil {
var start = 0
srOdds = [RewardOdds]()
for reward in rewardTable.values {
srOdds.append(RewardOdds(reward: reward, start: start, end: start + reward.relativeSROdds))
start += reward.relativeSROdds
}
}
}
/// merge gacha odds into local reward table
///
/// - Parameter gachaOdds: gacha odds from remote api
func merge(gachaOdds: GachaOdds) {
srRatio = ((gachaOdds.chargeRate[.sr]?.double() ?? 0) * 100).roundedInt()
ssrRatio = ((gachaOdds.chargeRate[.ssr]?.double() ?? 0) * 100).roundedInt()
rareRatio = ((gachaOdds.chargeRate[.r]?.double() ?? 0) * 100).roundedInt()
for (key, value) in gachaOdds.cardIDOdds {
rewardTable[key] = Reward(
cardId: key,
recommandOrder: rewardTable[key]?.recommandOrder ?? 0,
relativeOdds: (value.chargeOdds.double() * 10000).roundedInt(),
relativeSROdds: (value.srOdds.double() * 10000).roundedInt()
)
}
}
func simulateOnce(srGuarantee: Bool) -> Int {
if hasOdds {
generateOdds()
guard let arr = srGuarantee ? srOdds : odds, arr.count > 0, arr.last!.end > 0 else {
return 0
}
var index: Int?
repeat {
let rand = arc4random_uniform(UInt32(arr.last?.end ?? 0))
index = arr.firstIndex { $0.start <= Int(rand) && $0.end > Int(rand) }
} while index == nil
return arr[index!].reward.cardId
} else {
let rand = arc4random_uniform(10000)
var rarity: CGSSRarityTypes
switch rand {
case UInt32(rareRatio + srRatio)..<10000:
rarity = .ssr
case UInt32(rareRatio)..<UInt32(rareRatio + srRatio):
rarity = .sr
default:
rarity = .r
}
if srGuarantee && rarity == .r {
rarity = .sr
}
switch rarity {
case CGSSRarityTypes.ssr:
// 目前ssr新卡占40% sr新卡占20% r新卡占12%
if newssr.count > 0 && 100.proc(40) {
return newssr.random()!.cardId
} else if ssr.count > 0 {
return ssr.random()!.cardId
} else {
return 0
}
case CGSSRarityTypes.sr:
if newsr.count > 0 && 100.proc(20) {
return newsr.random()!.cardId
} else if sr.count > 0 {
return sr.random()!.cardId
} else {
return 0
}
case CGSSRarityTypes.r:
if newr.count > 0 && 100.proc(12) {
return newr.random()!.cardId
} else if r.count > 0 {
return r.random()!.cardId
} else {
return 0
}
default:
return 0
}
}
}
func simulate(times: Int, srGuaranteeCount: Int) -> [Int] {
var result = [Int]()
guard srGuaranteeCount <= times else {
fatalError("sr guarantees is greater than simulation times")
}
for i in 0..<times {
if i + srGuaranteeCount >= times {
result.append(simulateOnce(srGuarantee: true))
} else {
result.append(simulateOnce(srGuarantee: false))
}
}
return result
}
}
extension Double {
func roundedInt(digits: Int = 0) -> Int {
return Int(rounded(digits: digits))
}
}
extension String {
func double(`default`: Double = 0) -> Double {
return Double(self) ?? `default`
}
}
| mit | 72c7a4ae5114f8bc66194f3fd9c828a1 | 28.553191 | 156 | 0.4982 | 4.169606 | false | false | false | false |
clwm01/RTKitDemo | RCToolsDemo/RCToolsDemo/RTAudioStream.swift | 2 | 22584 | //
// AudioStreamer.swift
// RCToolsDemo
//
// Created by Rex Tsao on 3/11/16.
// Copyright (c) 2016 rexcao. All rights reserved.
//
// NOT FINISHED
// =====================================================================================================
// This software was created based on "AudioStreamer" in https://github.com/mattgallagher/AudioStreamer,
// this is merely the swift version of "AudioStreamer".
// Creation rights belong to the author of "mattgallagher/AudioStreamer".
// =====================================================================================================
//
// Declaration of original author is below:
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software. Permission is granted to anyone to
// use this software for any purpose, including commercial applications, and to
// alter it and redistribute it freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source
// distribution.
//
import Foundation
import AudioToolbox
import CFNetwork
enum RTAudioStreamState {
case Initialized
case StartingFileThread
case WaitingForData
case FlushingEOF
case WaitingForQueueToStart
case Playing
case Buffering
case Stopping
case Stopped
case Paused
}
enum RTAudioStreamStopReason {
case NoStop
case StoppingEOF
case StoppingUserAction
case StoppingError
case StoppingTemporarily
}
enum RTAudioStreamErrorCode {
case NoError
case NetworkConnectionFailed
case FileStreamGetPropertyFailed
case FileStreamSetPropertyFailed
case FileStreamSeekFailed
case FileStreamParseBytesFailed
case FileStreamOpenFailed
case FileStreamCloseFailed
case AudioDataNotFound
case AudioQueueCreationFailed
case AudioQueueBufferAllocationFailed
case AudioQueueEnqueueFailed
case AudioQueueAddListenerFailed
case AudioQueueRemoveListenerFailed
case AudioQueueStartFailed
case AudioQueuePauseFailed
case AudioQueueBufferMismatch
case AudioQueueDisposeFailed
case AudioQueueStopFailed
case AudioQueueFlushFailed
case AudioStreamFailed
case GetAudioTimeFailed
case AudioBufferTooSmall
}
class RTAudioStream: NSObject {
let LOG_QUEUED_BUFFERS = 0
/// Number of audio queue buffers we allocate. Needs to be big enough to keep audio pipeline
/// busy (non-zero number of queued buffers) but not so big that audio takes too long to begin
/// (kNumAQBufs * kAQBufSize of data must be loaded before playback will start).
///
/// Set LOG_QUEUED_BUFFERS to 1 to log how many buffers are queued at any time -- if it drops
/// to zero too often, this value may need to increase. Min 3, typical 8-24.
let kNumAQBufs = 16
/// Number of bytes in each audio queue buffer Needs to be big enough to hold a packet of
/// audio from the audio file. If number is too large, queuing of audio before playback starts
/// will take too long.
/// Highly compressed files can use smaller numbers (512 or less). 2048 should hold all
/// but the largest packets. A buffer size error will occur if this number is too small.
let kAQDefaultBufSize = 2048
/// Number of packet descriptions in our array
let kAQMaxPacketDescs = 512
private var url: NSURL?
/// Special threading consideration:
/// The audioQueue property should only ever be accessed inside a
/// synchronized(self) block and only *after* checking that ![self isFinishing]
private var audioQueue: AudioQueueRef?
/// The audio file stream parser.
private var audioFileStream: AudioFileStreamID?
/// Description of the audio
private var asbd: AudioStreamBasicDescription?
/// The thread where the download and audio file stream parsing occurs.
private var internalThread: NSThread?
/// Audio queue buffers.
private var audioQueueBuffer: [AudioQueueBufferRef]?
/// Packet descriptions for enquening audio
private var packetDescs: [AudioStreamPacketDescription]?
/// The index of the audioQueueBuffer that is being filled.
private var fillBufferIndex: Int?
private var packetBufferSize: UInt32?
/// How many bytes have been filled.
private var bytesFilled: size_t?
/// How many packets have been read
private var packetsFilled: size_t?
/// Flags to indicate that a buffer is still in use.
private var inUse: [Bool]?
private var bufferUsed: Int?
private var httpHeaders: NSDictionary?
private var fileExtension: String?
private var state: RTAudioStreamState?
// {
// get {
// objc_sync_enter(self)
// return self.state!
// objc_sync_exit(self)
// }
// set {
// }
// }
private var lastState: RTAudioStreamState?
private var stopReason: RTAudioStreamStopReason?
private var errorCode: RTAudioStreamErrorCode?
private var err: OSStatus?
/// Flag to indicate middle of the stream.
private var disContinuous: Bool?
/// A mutex to protect the inUse flags.
private var queueBuffersMutex: pthread_mutex_t?
/// A condition variable for handling the inUse flags.
private var queueBufferReadyCondition: pthread_cond_t?
private var stream: CFReadStreamRef?
private var notificationCenter: NSNotificationCenter?
/// Bits per second in the file.
private var bitRate: UInt32?
/// Offset of the first audio packet in the stream.
private var dataOffset: Int?
/// Length of the file in bytes.
private var fileLength: Int?
/// Seek offset within the file in bytes.
private var seekByteOffset: Int?
/// Used when the actual number of audio bytes in the file is known (more accurate than assuming the whole file is audio).
private var audioDataByteCount: UInt64?
/// Number of packets accumulated for bitrate estimation.
private var processedPacketsCount: UInt64?
/// Byte size of accumulated estimation packets.
private var processedPacketsSizeTotal: UInt64?
private var seekTime: Double?
private var seekWasRequested: Bool?
private var requestedSeekTime: Double?
/// Sample rate of the file (used to compare with samples played by the queue for current playback time).
private var sampleRate: Double?
/// Sample rate times frames per packet.
private var packetDuration: Double?
/// Last calculated progress point
private var lastProgress: Double?
private var pausedByInterruption: Bool?
// To control whether the alert is displayed in failWithErrorCode.
private var shouldDisplayAlertOnError: Bool?
private let BitRateEstimationMaxPackets = 5000
private let BitRateEstimationMinPackets = 50
static let ASStatusChangedNotification = "ASStatusChangedNotification"
static let ASAudioSessionInterruptionOccuredNotification = "ASAudioSessionInterruptionOccuredNotification"
static let NO_ERROR_STARTING = "No error."
static let FILE_STREAM_GET_PROPERTY_FAILED_STRING = "File stream get property failed."
static let FILE_STREAM_SEEK_FAILED_STRING = "File stream seek failed."
static let FILE_STREAM_PARSE_BYTES_FAILED_STRING = "Parse bytes failed."
static let FILE_STREAM_OPEN_FAILED_STRING = "Open audio file stream failed."
static let FILE_STREAM_CLOSE_FAILED_STRING = "Close audio file stream failed."
static let AUDIO_QUEUE_CREATION_FAILED_STRING = "Audio queue creation failed."
static let AUDIO_QUEUE_BUFFER_ALLOCATION_FAILED_STRING = "Audio buffer allocation failed."
static let AUDIO_QUEUE_ENQUEUE_FAILED_STRING = "Queueing of audio buffer failed."
static let AUDIO_QUEUE_ADD_LISTENER_FAILED_STRING = "Audio queue add listener failed."
static let AUDIO_QUEUE_REMOVE_LISTENER_FAILED_STRING = "Audio queue remove listener failed."
static let AUDIO_QUEUE_START_FAILED_STRING = "Audio queue start failed."
static let AUDIO_QUEUE_BUFFER_MISMATCH_STRING = "Audio queue buffers don't match."
static let AUDIO_QUEUE_DISPOSE_FAILED_STRING = "Audio queue dispose failed."
static let AUDIO_QUEUE_PAUSE_FAILED_STRING = "Audio queue pause failed."
static let AUDIO_QUEUE_STOP_FAILED_STRING = "Audio queue stop failed."
static let AUDIO_DATA_NOT_FOUND_STRING = "No audio data found."
static let AUDIO_QUEUE_FLUSH_FAILED_STRING = "Audio queue flush failed."
static let GET_AUDIO_TIME_FAILED_STRING = "Audio queue get current time failed."
static let AUDIO_STREAMER_FAILED_STRING = "Audio playback failed"
static let NETWORK_CONNECTION_FAILED_STRING = "Network connection failed"
static let AUDIO_BUFFER_TOO_SMALL_STRING = "Audio packets are larger than kAQDefaultBufSize."
private func handlePropertyChangeForFileStream(inAudioFileStream: AudioFileStreamID, fileStreamPropertyID inPropertyID: AudioFileStreamPropertyID, ioFlags: UInt32) {
}
private func handleAudioPackets(inInputData: AnyObject?, numberBytes inNumberBytes: UInt32, numberPackets inNumberPackets: UInt32, packetDescriptions inPacketDescriptions: AudioStreamPacketDescription) {
}
private func handleBufferCompleteForQueue(inAQ: AudioQueueRef, buffer inBuffer: AudioQueueBufferRef) {
}
private func handlePropertyChangeForQueue(inAQ: AudioQueueRef, propertyID inID: AudioQueuePropertyID) {
}
@objc private func handleInterruptionChangeToState(notification: NSNotification) {
}
private func internalSeekToTime(newSeekTime: Double) {
}
private func enqueueBuffer() {
}
private func handleReadFromStream(aStream: CFReadStreamRef, eventType: CFStreamEventType) {
}
}
/// MARK: Audio Callback Function Implementions
/// Receives notification when the AudioFileStream has audio packets to be
/// played. In response, this function creates the AudioQueue, getting it
/// ready to begin playback (playback won't begin until audio packets are
/// sent to the queue in ASEnqueueBuffer).
///
/// This function is adapted from Apple's example in AudioFileStreamExample with
/// kAudioQueueProperty_IsRunning listening added.
func ASPropertyListenerProc(inClientData: AnyObject?, inAudioFileStream: AudioFileStreamID, inPropertyID: AudioFileStreamPropertyID, ioFlags: UInt32) {
// This is called by audio file stream when it finds property values.
let streamer = inClientData as! RTAudioStream
streamer.handlePropertyChangeForFileStream(inAudioFileStream, fileStreamPropertyID: inPropertyID, ioFlags: ioFlags)
}
/// When the AudioStream has packets to be played, this function gets an
/// idle audio buffer and copies the audio packets into it. The calls to
/// ASEnqueueBuffer won't return until there are buffers available (or the
/// playback has been stopped).
///
/// This function is adapted from Apple's example in AudioFileStreamExample with
/// CBR functionality added.
func ASPacketsProc(inClientData: AnyObject?, inNumberBytes: UInt32, inNumberPackets: UInt32, inInputData: AnyObject?, inPacketDescriptions: AudioStreamPacketDescription) {
// This is called by audio file stream when it finds packets of audio.
let streamer = inClientData as! RTAudioStream
streamer.handleAudioPackets(inInputData, numberBytes: inNumberBytes, numberPackets: inNumberPackets, packetDescriptions: inPacketDescriptions)
}
/// Called from the AudioQueue when playback of specific buffers completes. This
/// function signals from the AudioQueue thread to the AudioStream thread that
/// the buffer is idle and available for copying data.
///
/// This function is unchanged from Apple's example in AudioFileStreamExample.
func ASAudioQueueOutputCallback(inClientData: AnyObject?, inAQ: AudioQueueRef, inBuffer: AudioQueueBufferRef) {
// This is called by the audio queue when it has finished decoding our data.
// The buffer is now free to be reused.
let streamer = inClientData as! RTAudioStream
streamer.handleBufferCompleteForQueue(inAQ, buffer: inBuffer)
}
/// Called from the AudioQueue when playback is started or stopped. This
/// information is used to toggle the observable "isPlaying" property and
/// set the "finished" flag.
func ASAudioQueueIsRunningCallback(inUserData: AnyObject?, inAQ: AudioQueueRef, inID: AudioQueuePropertyID) {
let streamer = inUserData as! RTAudioStream
streamer.handlePropertyChangeForQueue(inAQ, propertyID: inID)
}
/// Invoked when the audio session is interrupted (like when the phone rings).
func ASAudioSessionInterruptionListener(inClientData: AnyObject?, inInterruptionState: UInt32) {
NSNotificationCenter.defaultCenter().postNotificationName(RTAudioStream.ASAudioSessionInterruptionOccuredNotification, object: inInterruptionState as? AnyObject)
}
/// MARK: CFReadStream Callback Function Implementations
/// This is the callback for the CFReadStream from the network connection. This
/// is where all network data is passed to the AudioFileStream.
///
/// Invoked when an error occurs, the stream ends or we have data to read.
func ASReadStreamCallBack(aStream: CFReadStreamRef, eventType: CFStreamEventType, inClientInfo: AnyObject?) {
let streamer = inClientInfo as! RTAudioStream
streamer.handleReadFromStream(aStream, eventType: eventType)
}
extension RTAudioStream {
func initWithURL(aURL: NSURL) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(RTAudioStream.handleInterruptionChangeToState(_:)), name: RTAudioStream.ASAudioSessionInterruptionOccuredNotification, object: nil)
}
/// Returned true if the audio has reached a stopping condition
func isFinishing() -> Bool {
objc_sync_enter(self)
if (errorCode! != .NoError && state! != .Initialized) || ((state! == .Stopping || state! == .Stopped) && stopReason! != .StoppingTemporarily) {
return true
}
objc_sync_exit(self)
return false
}
func runLoopShouldExit() -> Bool {
objc_sync_enter(self)
if errorCode! != .NoError || (state! == .Stopped && stopReason! != .StoppingTemporarily) {
return true
}
objc_sync_exit(self)
return false
}
/// Converts an error code to a string that can be localized or presented
/// to the user.
///
/// - parameter anErrorCode: the error code to convert
/// :return: the string representation of the error code
func stringForErrorCode(anErrorCode: RTAudioStreamErrorCode) -> String {
var res = RTAudioStream.AUDIO_STREAMER_FAILED_STRING
switch anErrorCode {
case .NoError:
res = RTAudioStream.NO_ERROR_STARTING
case .FileStreamGetPropertyFailed:
res = RTAudioStream.FILE_STREAM_GET_PROPERTY_FAILED_STRING
case .FileStreamSeekFailed:
res = RTAudioStream.FILE_STREAM_SEEK_FAILED_STRING
case .FileStreamParseBytesFailed:
res = RTAudioStream.FILE_STREAM_PARSE_BYTES_FAILED_STRING
case .AudioQueueCreationFailed:
res = RTAudioStream.AUDIO_QUEUE_CREATION_FAILED_STRING
case .AudioQueueBufferAllocationFailed:
res = RTAudioStream.AUDIO_QUEUE_BUFFER_ALLOCATION_FAILED_STRING
case .AudioQueueEnqueueFailed:
res = RTAudioStream.AUDIO_QUEUE_ENQUEUE_FAILED_STRING
case .AudioQueueAddListenerFailed:
res = RTAudioStream.AUDIO_QUEUE_ADD_LISTENER_FAILED_STRING
case .AudioQueueRemoveListenerFailed:
res = RTAudioStream.AUDIO_QUEUE_REMOVE_LISTENER_FAILED_STRING
case .AudioQueueStartFailed:
res = RTAudioStream.AUDIO_QUEUE_START_FAILED_STRING
case .AudioQueueBufferMismatch:
res = RTAudioStream.AUDIO_QUEUE_BUFFER_MISMATCH_STRING
case .FileStreamOpenFailed:
res = RTAudioStream.FILE_STREAM_OPEN_FAILED_STRING
case .FileStreamCloseFailed:
res = RTAudioStream.FILE_STREAM_CLOSE_FAILED_STRING
case .AudioQueueDisposeFailed:
res = RTAudioStream.AUDIO_QUEUE_DISPOSE_FAILED_STRING
case .AudioQueuePauseFailed:
res = RTAudioStream.AUDIO_QUEUE_DISPOSE_FAILED_STRING
case .AudioQueueFlushFailed:
res = RTAudioStream.AUDIO_QUEUE_FLUSH_FAILED_STRING
case .AudioDataNotFound:
res = RTAudioStream.AUDIO_DATA_NOT_FOUND_STRING
case .GetAudioTimeFailed:
res = RTAudioStream.GET_AUDIO_TIME_FAILED_STRING
case .NetworkConnectionFailed:
res = RTAudioStream.NETWORK_CONNECTION_FAILED_STRING
case .AudioQueueStopFailed:
res = RTAudioStream.AUDIO_QUEUE_STOP_FAILED_STRING
case .AudioStreamFailed:
res = RTAudioStream.AUDIO_STREAMER_FAILED_STRING
case .AudioBufferTooSmall:
res = RTAudioStream.AUDIO_BUFFER_TOO_SMALL_STRING
default:
res = RTAudioStream.AUDIO_STREAMER_FAILED_STRING
}
return res
}
func presentAlertWithTitle(title: String, message: String) {
RTPrint.shareInstance().prt(title)
RTPrint.shareInstance().prt(message)
}
/// Sets the playback state to failed and logs the error.
func failWithErrorCode(anErrorCode: RTAudioStreamErrorCode) {
objc_sync_enter(self)
if errorCode! != .NoError {
// Only set the error once.
return
}
errorCode = anErrorCode
if err != nil {
RTPrint.shareInstance().prt(err)
} else {
self.stringForErrorCode(anErrorCode)
}
if state! == .Playing || state! == .Paused || state! == .Buffering {
self.state = .Stopping
stopReason = .StoppingError
AudioQueueStop(audioQueue!, true)
}
if self.shouldDisplayAlertOnError! {
self.presentAlertWithTitle("Errors", message: "Unable to configure network read stream")
}
objc_sync_exit(self)
}
/// Method invoked on main thread to send notifications to the main thread's
/// notification center.
func mainThreadStateNotification() {
let notification = NSNotification(name: RTAudioStream.ASStatusChangedNotification, object: self)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
/// Sets the state and sends a notification that the state has changed.
/// - parameter anErrorCode: The error condition
func setSate(aStatus: RTAudioStreamState) {
objc_sync_enter(self)
if state! != aStatus {
state = aStatus
if NSThread.currentThread().isEqual(NSThread.mainThread()) {
self.mainThreadStateNotification()
} else {
}
}
objc_sync_exit(self)
}
/// Returns true if the audio currently playing.
func isPlaying() -> Bool {
if state! == .Playing {
return true
}
return false
}
/// Returns true if the audio currently playing.
func isPaused() -> Bool {
if state! == .Paused {
return true
}
return false
}
/// Returns true if the AudioStreamer is waiting for a state transition of some
/// kind.
func isWaiting() -> Bool {
objc_sync_enter(self)
if self.isFinishing() || state! == .StartingFileThread || state! == .WaitingForData || state! == .WaitingForQueueToStart || state! == .Buffering {
return true
}
objc_sync_exit(self)
return false
}
/// Returns true if the AudioStream is in the .Initialized state (i.e.
/// isn't doing anything).
func isIdle() -> Bool {
if state! == .Initialized {
return true
}
return false
}
/// Returns true if the AudioStream was stopped due to some errror, handled through failWithCodeError.
func isAborted() -> Bool {
if state! == .Stopping && stopReason! == .StoppingError {
return true
}
return false
}
/// Generates a first guess for the file type based on the file's extension
/// - parameter fileExtension: the file extension
///
/// :return: Returns a file type hint that can be passed to the AudioFileStream
func hintForFileExtension(fileExtension: String) ->AudioFileTypeID {
var fileTypeHint: AudioFileTypeID?
switch fileExtension {
case "mp3":
fileTypeHint = kAudioFileMP3Type
break
case "wav":
fileTypeHint = kAudioFileWAVEType
break
case "aifc":
fileTypeHint = kAudioFileAIFCType
break
case "aiff":
fileTypeHint = kAudioFileAIFFType
break
case "m4a":
fileTypeHint = kAudioFileM4AType
break
case "mp4":
fileTypeHint = kAudioFileMPEG4Type
break
case "caf":
fileTypeHint = kAudioFileCAFType
break
case "aac":
fileTypeHint = kAudioFileAAC_ADTSType
break
default:
fileTypeHint = kAudioFileAAC_ADTSType
break
}
return UInt32(fileTypeHint!)
}
/// Open the audioFileStream to parse data and the fileHandle as the data
/// source.
func openReadStream() {
objc_sync_enter(self)
// Create the HTTP GET request.
_ = CFHTTPMessageCreateRequest(nil, "GET", url!, kCFHTTPVersion1_1)
// If we are creating this request to seek to a location, set the requested byte
// range in the headers.
if fileLength! > 0 && seekByteOffset! > 0 {
_ = Double(seekByteOffset!)
_ = Double(fileLength!)
/// MARK: Stopped at here
}
///
objc_sync_exit(self)
}
}
| mit | 8e5ef27e638b0bb233fc1132ad3b65f9 | 39.913043 | 214 | 0.6846 | 4.677713 | false | false | false | false |
asp2insp/CodePathFinalProject | Pretto/Friend.swift | 2 | 3140 | //
// Friend.swift
// Pretto
//
// Created by Baris Taze on 6/14/15.
// Copyright (c) 2015 Pretto. All rights reserved.
//
import Foundation
private let kClassName = "Friend"
private let kFacebookId = "facebookId"
class Friend : PFObject, PFSubclassing {
override class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0;
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
static func parseClassName() -> String {
return kClassName
}
@NSManaged var facebookId : String
@NSManaged var friendName : String
@NSManaged var friendFacebookId : String
func printDebug() {
println("\(self.facebookId) - \(self.friendFacebookId) - \(self.friendName)")
}
class func printDebugAll(friends:[Friend]) {
for friend in friends {
friend.printDebug()
}
}
class func getAllFriendsFromFacebook(myFacebookId:String, onComplete:(([Friend]?)->Void)) {
var request = FBSDKGraphRequest(graphPath: "me/friends", parameters: nil)
request.startWithCompletionHandler { (conn:FBSDKGraphRequestConnection!, res:AnyObject!, err:NSError!) -> Void in
if err == nil && res != nil {
var friends:[Friend] = []
var friendsDataList = (res as! NSDictionary)["data"] as! NSArray
for data in friendsDataList {
var friendData = data as! NSDictionary
var friend = Friend()
friend.facebookId = myFacebookId
friend.friendFacebookId = friendData["id"] as! String
friend.friendName = friendData["name"] as! String
friends.append(friend)
}
onComplete(friends)
}
else {
onComplete(nil)
}
}
}
class func getAllFriendsFromDBase(facebookId: String, onComplete: ([Friend]? -> Void) ) {
let query = PFQuery(className: kClassName, predicate: nil)
query.whereKey(kFacebookId, equalTo: facebookId)
query.findObjectsInBackgroundWithBlock { (items, error) -> Void in
if error == nil {
var friends : [Friend] = []
for obj in items ?? [] {
if let friend = obj as? Friend {
friends.append(friend)
}
}
onComplete(friends)
}
else {
onComplete(nil)
}
}
}
class func subtract(those:[Friend], from:[Friend]) -> [Friend] {
if from.count <= 0 {
return those;
}
var hash = [String: Friend]()
for f in those {
hash[f.friendFacebookId] = f
}
var result = [Friend]()
for f in from {
if hash[f.friendFacebookId] == nil {
result.append(f)
}
}
return result
}
}
| mit | e0ba11ea51bb18769f39ae73130022e6 | 29.192308 | 121 | 0.516879 | 4.823349 | false | false | false | false |
benlangmuir/swift | test/IDE/complete_sself.swift | 13 | 5141 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t
// NOSELF: Begin completions
// NOSELF-NOT: name=Self
// NOSELF: End completions
// GENERICPARAM: Begin completions
// GENERICPARAM: Decl[GenericTypeParam]/Local: Self[#Self#];
// STATICSELF: Begin completions
// STATICSELF: Keyword[Self]/CurrNominal: Self[#S#];
// DYNAMICSELF: Begin completions
// DYNAMICSELF: Keyword[Self]/CurrNominal: Self[#Self#];
func freeFunc() {
#^GLOBAL_BODY_EXPR?check=NOSELF^#
let _: #^GLOBAL_BODY_TYPE?check=NOSELF^#
}
var freeVar: String {
"\(#^GLOBAL_VARBODY_EXPR?check=NOSELF^#)"
}
func freeFunc(x: #^GLOBAL_FUNC_PARAMTYPE?check=NOSELF^#) {}
func freeFunc(x: Int = #^GLOBAL_FUNC_DEFAULTEXPR?check=NOSELF^#) {}
func freeFunc(x: Int) -> #^GLOBAL_FUNC_RESULTTYPE?check=NOSELF^# {}
var x: ^#GLOBAL_VAR_TYPE^#
func sync() {}
protocol P {
func protoMeth(x: #^PROTOCOL_FUNC_PARAMTYPE?check=GENERICPARAM^#)
func protoMeth(x: Int) -> #^PROTOCOL_FUNC_RESULTTYPE?check=GENERICPARAM^#
subscript(x: #^PROTOCOL_SUBSCRIPT_PARAMTYPE?check=GENERICPARAM^#) -> Int { get }
subscript(y: Int) -> #^PROTOCOL_SUBSCRIPT_RESULTTYPE?check=GENERICPARAM^# { get }
var x: #^PROTOCOL_VAR_TYPE?check=GENERICPARAM^#
}
extension P {
func method(x: #^PROTOEXT_FUNC_PARAMTYPE?check=GENERICPARAM^#) { }
func method(x: Int = #^PROTOEXT_FUNC_DEFAULTEXPR?check=GENERICPARAM^#) { }
func method(x: Int) -> #^PROTOEXT_FUNC_RESULTTYPE?check=GENERICPARAM^# { }
subscript(x: #^PROTOEXT_SUBSCRIPT_PARAMTYPE?check=GENERICPARAM^#) -> Int { }
subscript(y: Int) -> #^PROTOEXT_SUBSCRIPT_RESULTTYPE?check=GENERICPARAM^# { }
var x: #^PROTOEXT_VAR_TYPE?check=GENERICPARAM^# { }
func bodyTest() {
#^PROTOEXT_BODY_EXPR?check=GENERICPARAM^#
let _: #^PROTOEXT_BODY_TYPE?check=GENERICPARAM^#
}
var varTest: String {
"\(#^PROTOEXT_VARBODY_EXPR?check=GENERICPARAM^#)"
}
}
struct S {
func method(x: #^STRUCT_FUNC_PARAMTYPE?check=STATICSELF^#)
func method(x: Int = #^STRUCT_FUNC_DEFAULTEXPR?check=STATICSELF^#) { }
func method(x: Int) -> #^STRUCT_FUNC_RESULTTYPE?check=STATICSELF^#
subscript(x: #^STRUCT_SUBSCRIPT_PARAMTYPE?check=STATICSELF^#) -> Int { get }
subscript(y: Int) -> #^STRUCT_SUBSCRIPT_RESULTTYPE?check=STATICSELF^# { get }
var x: #^STRUCT_VAR_TYPE?check=STATICSELF^#
func bodyTest() {
#^STRUCT_BODY_EXPR?check=STATICSELF^#
let _: #^STRUCT_BODY_TYPE?check=STATICSELF^#
}
var varTest: String {
"\(#^STRUCT_VARBODY_EXPR?check=STATICSELF^#)"
}
}
extension S {
func method(x: #^STRUCTEXT_FUNC_PARAMTYPE?check=STATICSELF^#)
func method(x: Int = #^STRUCTEXT_FUNC_DEFAULTEXPR?check=STATICSELF^#) { }
func method(x: Int) -> #^STRUCTEXT_FUNC_RESULTTYPE?check=STATICSELF^#
subscript(x: #^STRUCTEXT_SUBSCRIPT_PARAMTYPE?check=STATICSELF^#) -> Int { get }
subscript(y: Int) -> #^STRUCTEXT_SUBSCRIPT_RESULTTYPE?check=STATICSELF^# { get }
var x: #^STRUCTEXT_VAR_TYPE?check=STATICSELF^#
func bodyTest() {
#^STRUCTEXT_BODY_EXPR?check=STATICSELF^#
let _: #^STRUCTEXT_BODY_TYPE?check=STATICSELF^#
}
var varTest: String {
"\(#^STRUCTEXT_VARBODY_EXPR?check=STATICSELF^#)"
}
}
class C {
func method(x: #^CLASS_FUNC_PARAMTYPE?check=NOSELF^#)
func method(x: Int = #^CLASS_FUNC_DEFAULTEXPR?check=NOSELF^#) { }
func method(x: Int) -> #^CLASS_FUNC_RESULTTYPE?check=DYNAMICSELF^#
subscript(x: #^CLASS_SUBSCRIPT_PARAMTYPE?check=NOSELF^#) -> Int { get }
subscript(y: Int) -> #^CLASS_SUBSCRIPT_RESULTTYPE?check=DYNAMICSELF^# { get }
var x: #^CLASS_VAR_TYPE?check=DYNAMICSELF^#
func bodyTest() {
#^CLASS_BODY_EXPR?check=DYNAMICSELF^#
let _: #^CLASS_BODY_TYPE?check=DYNAMICSELF^#
}
var varTest: String {
"\(#^CLASS_VARBODY_EXPR?check=DYNAMICSELF^#)"
}
}
class CC {}
extension CC {
func method(x: #^CLASSEXT_FUNC_PARAMTYPE?check=NOSELF^#)
func method(x: Int = #^CLASSEXT_FUNC_DEFAULTEXPR?check=NOSELF^#) { }
func method(x: Int) -> #^CLASSEXT_FUNC_RESULTTYPE?check=DYNAMICSELF^#
subscript(x: #^CLASSEXT_SUBSCRIPT_PARAMTYPE?check=NOSELF^#) -> Int { get }
subscript(y: Int) -> #^CLASSEXT_SUBSCRIPT_RESULTTYPE?check=DYNAMICSELF^# { get }
var x: #^CLASSEXT_VAR_TYPE?check=DYNAMICSELF^#
func bodyTest() {
#^CLASSEXT_BODY_EXPR?check=DYNAMICSELF^#
let _: #^CLASSEXT_BODY_TYPE?check=DYNAMICSELF^#
}
var varTest: String {
"\(#^CLASSEXT_VARBODY_EXPR?check=DYNAMICSELF^#)"
}
}
class CCC {
func bodyTest() {
func inner() {
#^CLASS_NESTEDBODY_EXPR?check=DYNAMICSELF^#
let _: #^CLASS_NESTEDBODY_TYPE?check=DYNAMICSELF^#
}
func inner(x: #^CLASS_NESTEDFUNC_PARAMTYPE?check=DYNAMICSELF^#) {}
func inner(y: Int = #^CLASS_NESTEDFUNC_DEFAULTEXPR?check=DYNAMICSELF^#) {}
func inner() -> #^CLASS_NESTEDFUNC_RESULTTYPE?check=DYNAMICSELF^# {}
typealias A<T> = #^CLASS_TYPEALIAS_TYPE?check=DYNAMICSELF^#
}
class Inner {
func method() {
#^CLASS_NESTEDTYPE_EXPR?check=DYNAMICSELF^#
let _: #^CLASS_NESTEDTYPE_TYPE?check=DYNAMICSELF^#
}
}
}
| apache-2.0 | e6fc45f572d3811097d2cd0f12ede0c9 | 32.383117 | 125 | 0.673215 | 3.201121 | false | true | false | false |
StratusHunter/JustEat-Test-Swift | JustEat/ViewControllers/ViewController.swift | 1 | 3788 | //
// ViewController.swift
// JustEat
//
// Created by Terence Baker on 11/05/2016.
// Copyright (c) 2016 Bulb Studios Ltd. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
import RxAlamofire
import ObjectMapper
class ViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
private let bag = DisposeBag()
private var resturantArray = Variable<[Resturant]>([])
override func viewDidLoad() {
super.viewDidLoad()
//Adaptive cell height
tableView.estimatedRowHeight = 60.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.rx_setDelegate(self)
performUIBindings()
}
private func searchWithPostcode(postcode: String) {
guard let observer = JustEatService.resturantSearchObservable(postcode) else {
return
}
observer.observeOn(ConcurrentDispatchQueueScheduler(globalConcurrentQueueQOS: .Background))
.map {
guard let resturantJSON = $0["Restaurants"] else {
print("Error parsing JSON")
return nil
}
return Mapper<Resturant>().mapArray(resturantJSON)
}
.observeOn(MainScheduler.instance)
.subscribe(onNext: {
[unowned self] json in
self.parseJSON(json)
})
.addDisposableTo(bag)
}
private func parseJSON(json: [Resturant]?) {
guard let resturants = json else {
return
}
self.setResturantArray(resturants)
}
private func clearSearch() {
setResturantArray([Resturant]())
}
private func setResturantArray(resturants: [Resturant]) {
self.resturantArray.value.removeAll(keepCapacity: false)
self.resturantArray.value += resturants
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
searchBar.resignFirstResponder()
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
searchBar.resignFirstResponder()
}
}
//UI Bindings using Rx
extension ViewController {
func performUIBindings() {
bindArrayToTableView()
subscribeSearchChange()
}
private func bindArrayToTableView() {
//Creates a binding between the array having values and the tableview being shown/hidden
resturantArray.asObservable()
.map {
$0.isEmpty
}
.bindTo(tableView.rx_hidden)
.addDisposableTo(bag)
//Creates a binding to the array and the tableview to load the cells
resturantArray.asObservable()
.bindTo(tableView.rx_itemsWithCellIdentifier(R.reuseIdentifier.resturantCell.identifier, cellType: ResturantCell.self)) {
(_, element, cell) in
cell.setupWithResturant(element)
}
.addDisposableTo(bag)
}
private func subscribeSearchChange() {
//Dismiss keyboard when search is pressed
searchBar.rx_searchButtonClicked
.subscribeNext {
[unowned self] in
self.searchBar.resignFirstResponder()
}
//Use rx to monitor text changes in the search bar. Avoids hammering the API using the throttle command and will not perform a search on the same text input.
searchBar.rx_text
.throttle(0.4, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.subscribeNext {
[unowned self] (postcode: String) in
postcode.characters.count == 0 ? self.clearSearch() : self.searchWithPostcode(postcode)
}
.addDisposableTo(bag)
}
}
| mit | ec76b8489a591d1be954bb5e0924cab9 | 24.422819 | 165 | 0.644667 | 4.951634 | false | false | false | false |
babarqb/HackingWithSwift | project3/Project1/DetailViewController.swift | 24 | 1793 | //
// DetailViewController.swift
// Project1
//
// Created by Hudzilla on 13/09/2015.
// Copyright © 2015 Paul Hudson. All rights reserved.
//
import Social
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var detailImageView: UIImageView!
var detailItem: String? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let imageView = self.detailImageView {
imageView.image = UIImage(named: detail)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "shareTapped")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnTap = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.hidesBarsOnTap = false
}
func shareTapped() {
let vc = UIActivityViewController(activityItems: [detailImageView.image!], applicationActivities: [])
presentViewController(vc, animated: true, completion: nil)
}
// func shareTapped() {
// let vc = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
// vc.setInitialText("Look at this great picture!")
// vc.addImage(detailImageView.image!)
// vc.addURL(NSURL(string: "http://www.photolib.noaa.gov/nssl"))
// presentViewController(vc, animated: true, completion: nil)
// }
}
| unlicense | 37c90805fd2be89a44839eab65b07cf7 | 24.6 | 120 | 0.734375 | 4 | false | false | false | false |
hanhailong/practice-swift | HealthKit/Read and Write Health Data/Read and Write Health Data/ViewController.swift | 2 | 5516 | //
// ViewController.swift
// Read and Write Health Data
//
// Created by Domenico Solazzo on 08/05/15.
// License MIT
//
import UIKit
import HealthKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var saveButton: UIButton!
/*
This is the label that shows the user's weight unit (Kilograms)
the righthand side of our text field
*/
let textFieldRightLabel = UILabel(frame: CGRectZero)
// Weight
let weightQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)
// Health kit store
lazy var healthStore = HKHealthStore()
override func viewDidLoad() {
super.viewDidLoad()
textField.rightView = textFieldRightLabel
textField.rightViewMode = .Always
}
// Information that we would write into the HealthKit
lazy var typesToShare: Set<NSObject> = {
return Set<NSObject>(arrayLiteral: self.weightQuantityType)
}()
// We want to read these types of data */
lazy var typesToRead: Set<NSObject> = {
return Set<NSObject>(arrayLiteral:
self.weightQuantityType
)
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Check if the HealthKit is available
if HKHealthStore.isHealthDataAvailable(){
// Request authorization
healthStore.requestAuthorizationToShareTypes(typesToShare,
readTypes: typesToRead){[weak self](succeeded: Bool, error: NSError!) in
let strongSelf = self!
if succeeded && error == nil{
strongSelf.readWeightInformation()
}else{
if let theError = error{
println("Error \(theError)")
}
}
}
}else{
println("HealthData is not available")
}
}
func readWeightInformation(){
// Sorting. Descending.
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
// Set the query
let query = HKSampleQuery(sampleType: weightQuantityType,
predicate: nil,
limit: 1,
sortDescriptors: [sortDescriptor],
resultsHandler: {[weak self] (query: HKSampleQuery!,
results: [AnyObject]!,
error: NSError!) in
if results.count > 0{
/* We really have only one sample */
let sample = results[0] as! HKQuantitySample
/* Get the weight in kilograms from the quantity */
let weightInKilograms = sample.quantity.doubleValueForUnit(
HKUnit.gramUnitWithMetricPrefix(.Kilo))
/* This is the value of KG, localized in user's language */
let formatter = NSMassFormatter()
let kilogramSuffix = formatter.unitStringFromValue(weightInKilograms,
unit: .Kilogram)
dispatch_async(dispatch_get_main_queue(), {
let strongSelf = self!
/* Set the value of KG on the righthand side of the
text field */
strongSelf.textFieldRightLabel.text = kilogramSuffix
strongSelf.textFieldRightLabel.sizeToFit()
/* And finally set the text field's value to the user's
weight */
let weightFormattedAsString =
NSNumberFormatter.localizedStringFromNumber(
NSNumber(double: weightInKilograms),
numberStyle: .NoStyle)
strongSelf.textField.text = weightFormattedAsString
})
} else {
print("Could not read the user's weight ")
println("or no weight data was available")
}
})
// Execute the query
healthStore.executeQuery(query)
}
// Saving
@IBAction func saveUserWeight(){
let kilogramUnit = HKUnit.gramUnitWithMetricPrefix(HKMetricPrefix.Kilo)
let weightQuantity = HKQuantity(unit: kilogramUnit,
doubleValue: (textField.text as NSString).doubleValue)
let now = NSDate()
let sample = HKQuantitySample(type: weightQuantityType,
quantity: weightQuantity,
startDate: now,
endDate: now)
healthStore.saveObject(sample, withCompletion: {
(succeeded: Bool, error: NSError!) in
if error == nil{
println("Successfully saved the user's weight")
} else {
println("Failed to save the user's weight")
}
})
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| mit | c8558ac48e5e581ff89da3e3407fa7df | 34.133758 | 103 | 0.527012 | 6.115299 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/ios/Swift/ModuleHolder.swift | 2 | 5198 | import Dispatch
/**
Holds a reference to the module instance and caches its definition.
*/
public final class ModuleHolder {
/**
Instance of the module.
*/
private(set) var module: AnyModule
/**
A weak reference to the app context.
*/
private(set) weak var appContext: AppContext?
/**
JavaScript object that represents the module instance in the runtime.
*/
public internal(set) lazy var javaScriptObject: JavaScriptObject? = createJavaScriptModuleObject()
/**
Caches the definition of the module type.
*/
let definition: ModuleDefinition
/**
Returns `definition.name` if not empty, otherwise falls back to the module type name.
*/
var name: String {
return definition.name.isEmpty ? String(describing: type(of: module)) : definition.name
}
/**
Shortcut to get the underlying view manager definition.
*/
var viewManager: ViewManagerDefinition? {
return definition.viewManager
}
/**
Number of JavaScript listeners attached to the module.
*/
var listenersCount: Int = 0
init(appContext: AppContext, module: AnyModule) {
self.appContext = appContext
self.module = module
self.definition = module.definition()
post(event: .moduleCreate)
}
// MARK: Constants
/**
Merges all `constants` definitions into one dictionary.
*/
func getConstants() -> [String: Any?] {
return definition.constants.reduce(into: [String: Any?]()) { dict, definition in
dict.merge(definition.body()) { $1 }
}
}
// MARK: Calling functions
func call(function functionName: String, args: [Any], promise: Promise) {
do {
guard let function = definition.functions[functionName] else {
throw FunctionNotFoundException((functionName: functionName, moduleName: self.name))
}
let queue = function.queue ?? DispatchQueue.global(qos: .default)
queue.async {
function.call(args: args, promise: promise)
}
} catch let error as CodedError {
promise.reject(error)
} catch {
promise.reject(UnexpectedException(error))
}
}
func call(function functionName: String, args: [Any], _ callback: @escaping (Any?, CodedError?) -> Void = { _, _ in }) {
let promise = Promise {
callback($0, nil)
} rejecter: {
callback(nil, $0)
}
call(function: functionName, args: args, promise: promise)
}
@discardableResult
func callSync(function functionName: String, args: [Any]) -> Any? {
if let function = definition.functions[functionName] {
return function.callSync(args: args)
}
return nil
}
// MARK: JavaScript Module Object
/**
Creates the JavaScript object that will be used to communicate with the native module.
The object is prefilled with module's constants and functions.
JavaScript can access it through `global.ExpoModules[moduleName]`.
- Note: The object will be `nil` when the runtime is unavailable (e.g. remote debugger is enabled).
*/
private func createJavaScriptModuleObject() -> JavaScriptObject? {
// It might be impossible to create any object at the moment (e.g. remote debugging, app context destroyed)
guard let object = appContext?.runtime?.createObject() else {
return nil
}
// Fill in with constants
for (key, value) in getConstants() {
object[key] = value
}
// Fill in with functions
for (_, fn) in definition.functions {
if fn.isAsync {
object.setAsyncFunction(fn.name, argsCount: fn.argumentsCount, block: createAsyncFunctionBlock(holder: self, name: fn.name))
} else {
object.setSyncFunction(fn.name, argsCount: fn.argumentsCount, block: createSyncFunctionBlock(holder: self, name: fn.name))
}
}
return object
}
// MARK: Listening to native events
func listeners(forEvent event: EventName) -> [EventListener] {
return definition.eventListeners.filter {
$0.name == event
}
}
func post(event: EventName) {
listeners(forEvent: event).forEach {
try? $0.call(module, nil)
}
}
func post<PayloadType>(event: EventName, payload: PayloadType?) {
listeners(forEvent: event).forEach {
try? $0.call(module, payload)
}
}
// MARK: JavaScript events
/**
Modifies module's listeners count and calls `onStartObserving` or `onStopObserving` accordingly.
*/
func modifyListenersCount(_ count: Int) {
if count > 0 && listenersCount == 0 {
_ = definition.functions["startObserving"]?.callSync(args: [])
} else if count < 0 && listenersCount + count <= 0 {
_ = definition.functions["stopObserving"]?.callSync(args: [])
}
listenersCount = max(0, listenersCount + count)
}
// MARK: Deallocation
deinit {
post(event: .moduleDestroy)
}
// MARK: - Exceptions
internal class ModuleNotFoundException: GenericException<String> {
override var reason: String {
"Module '\(param)' not found"
}
}
internal class FunctionNotFoundException: GenericException<(functionName: String, moduleName: String)> {
override var reason: String {
"Function '\(param.functionName)' not found in module '\(param.moduleName)'"
}
}
}
| bsd-3-clause | 013cc9fb8a8c7dd828326267ec075409 | 27.404372 | 132 | 0.668142 | 4.271159 | false | false | false | false |
ken0nek/swift | test/1_stdlib/FloatingPointIR.swift | 1 | 2316 | // RUN: %target-build-swift -emit-ir %s | FileCheck -check-prefix=%target-cpu %s
// REQUIRES: executable_test
var globalFloat32 : Float32 = 0.0
var globalFloat64 : Float64 = 0.0
#if arch(i386) || arch(x86_64)
var globalFloat80 : Float80 = 0.0
#endif
@inline(never)
func acceptFloat32(_ a: Float32) {
globalFloat32 = a
}
@inline(never)
func acceptFloat64(_ a: Float64) {
globalFloat64 = a
}
#if arch(i386) || arch(x86_64)
@inline(never)
func acceptFloat80(_ a: Float80) {
globalFloat80 = a
}
#endif
func testConstantFoldFloatLiterals() {
acceptFloat32(1.0)
acceptFloat64(1.0)
#if arch(i386) || arch(x86_64)
acceptFloat80(1.0)
#endif
}
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// i386: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// x86_64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat80FVs7Float80T_(x86_fp80 0xK3FFF8000000000000000)
// armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// armv7: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// armv7k: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// arm64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// powerpc64: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// powerpc64le: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
// s390x: call void @{{.*}}_TF15FloatingPointIR13acceptFloat32FSfT_(float 1.000000e+00)
// s390x: call void @{{.*}}_TF15FloatingPointIR13acceptFloat64FSdT_(double 1.000000e+00)
| apache-2.0 | f4fa96c7ddd6d40e969a131c0f0e1770 | 38.931034 | 110 | 0.740069 | 3.285106 | false | false | false | false |
the-hypermedia-project/representor-swift | Sources/HTTPTransition.swift | 1 | 1669 | //
// HTTPTransition.swift
// Representor
//
// Created by Kyle Fuller on 23/01/2015.
// Copyright (c) 2015 Apiary. All rights reserved.
//
import Foundation
/** An implementation of the Transition protocol for HTTP. */
public struct HTTPTransition : TransitionType {
public typealias Builder = HTTPTransitionBuilder
public var uri:String
/// The HTTP Method that should be used to make the request
public var method:String
/// The suggested contentType that should be used to make the request
public var suggestedContentTypes:[String]
public var attributes:InputProperties
public var parameters:InputProperties
public init(uri:String, attributes:InputProperties? = nil, parameters:InputProperties? = nil) {
self.uri = uri
self.attributes = attributes ?? [:]
self.parameters = parameters ?? [:]
self.method = "GET"
self.suggestedContentTypes = [String]()
}
public init(uri:String, _ block:((_ builder:Builder) -> ())) {
let builder = Builder()
block(builder)
self.uri = uri
self.attributes = builder.attributes
self.parameters = builder.parameters
self.method = builder.method
self.suggestedContentTypes = builder.suggestedContentTypes
}
public var hashValue:Int {
return uri.hashValue
}
}
public func ==(lhs:HTTPTransition, rhs:HTTPTransition) -> Bool {
return (
lhs.uri == rhs.uri &&
lhs.attributes == rhs.attributes &&
lhs.parameters == rhs.parameters &&
lhs.method == rhs.method &&
lhs.suggestedContentTypes == rhs.suggestedContentTypes
)
}
| mit | a2da67448060f9f909762f4aee80066a | 27.288136 | 99 | 0.658478 | 4.585165 | false | false | false | false |
giridharvc7/ScreenRecord | ScreenRecordDemo/Source/ScreenRecorder.swift | 1 | 3174 | //
// ScreenRecorder.swift
// BugReporterTest
//
// Created by Giridhar on 09/06/17.
// Copyright © 2017 Giridhar. All rights reserved.
//
import Foundation
import ReplayKit
import AVKit
class ScreenRecorder
{
var assetWriter:AVAssetWriter!
var videoInput:AVAssetWriterInput!
let viewOverlay = WindowUtil()
//MARK: Screen Recording
func startRecording(withFileName fileName: String, recordingHandler:@escaping (Error?)-> Void)
{
if #available(iOS 11.0, *)
{
let fileURL = URL(fileURLWithPath: ReplayFileUtil.filePath(fileName))
assetWriter = try! AVAssetWriter(outputURL: fileURL, fileType:
AVFileType.mp4)
let videoOutputSettings: Dictionary<String, Any> = [
AVVideoCodecKey : AVVideoCodecType.h264,
AVVideoWidthKey : UIScreen.main.bounds.size.width,
AVVideoHeightKey : UIScreen.main.bounds.size.height
];
videoInput = AVAssetWriterInput (mediaType: AVMediaType.video, outputSettings: videoOutputSettings)
videoInput.expectsMediaDataInRealTime = true
assetWriter.add(videoInput)
RPScreenRecorder.shared().startCapture(handler: { (sample, bufferType, error) in
// print(sample,bufferType,error)
recordingHandler(error)
if CMSampleBufferDataIsReady(sample)
{
if self.assetWriter.status == AVAssetWriterStatus.unknown
{
self.assetWriter.startWriting()
self.assetWriter.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sample))
}
if self.assetWriter.status == AVAssetWriterStatus.failed {
print("Error occured, status = \(self.assetWriter.status.rawValue), \(self.assetWriter.error!.localizedDescription) \(String(describing: self.assetWriter.error))")
return
}
if (bufferType == .video)
{
if self.videoInput.isReadyForMoreMediaData
{
self.videoInput.append(sample)
}
}
}
}) { (error) in
recordingHandler(error)
// debugPrint(error)
}
} else
{
// Fallback on earlier versions
}
}
func stopRecording(handler: @escaping (Error?) -> Void)
{
if #available(iOS 11.0, *)
{
RPScreenRecorder.shared().stopCapture
{ (error) in
handler(error)
self.assetWriter.finishWriting
{
print(ReplayFileUtil.fetchAllReplays())
}
}
} else {
// Fallback on earlier versions
}
}
}
| mit | 8ca886dba87f1cb5a10b75f644e691cf | 32.4 | 187 | 0.512764 | 5.717117 | false | false | false | false |
AnnMic/FestivalArchitect | FestivalArchitect/Classes/AIStates/AIStateQuenchHunger.swift | 1 | 1042 | //
// AnimateComponent.swift
// Festival
//
// Created by Ann Michelsen on 01/10/14.
// Copyright (c) 2014 Ann Michelsen. All rights reserved.
//
import Foundation
class AIStateQuenchHunger : AIState {
override func name() -> String {
return "QuenchHunger"
}
override func enter(entity:Entity) {
println("Buying a Döööner")
}
override func execute(entity:Entity, aiSystem:AISystem) {
println("Eating someting")
//remove money?
var render:RenderComponent = entity.component(RenderComponent)!
render.sprite.color = CCColor.yellowColor()
var visitor:PhysicalNeedComponent = entity.component(PhysicalNeedComponent)!
if visitor.hunger < 70 {
visitor.hunger += 30
}
else{
visitor.hunger = 100
}
aiSystem.changeStateForEntity(entity)
}
override func exit(entity:Entity) {
println("Not hungry anymore! :)")
}
}
| mit | 040f246562249c531c57ef39ea2d5111 | 20.645833 | 84 | 0.587103 | 4.293388 | false | false | false | false |
jmelberg/acmehealth-swift | AcmeHealth/RequestAppointmentViewController.swift | 1 | 5015 | /** Author: Jordan Melberg **/
/** Copyright © 2016, Okta, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
class RequestAppointmentViewController: UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@available(iOS 2.0, *)
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
@IBOutlet weak var date: UIDatePicker!
@IBOutlet weak var doctorLabel: UILabel!
@IBOutlet weak var doctorPicker: UIPickerView!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var reasonText: UITextView!
@IBAction func datePickerValue(sender: AnyObject) {
datePickerChanged()
}
@IBAction func requestAppointment(sender: AnyObject) {
if date != nil || doctorLabel != nil || reasonText != nil{
requestAppointment()
} else {
print("Missing fields")
}
}
@IBAction func exitRequest(sender: AnyObject) {
self.navigationController?.popViewController(animated: true)
}
var datePickerHidden = true
var pickerHidden = true
override func viewDidLoad() {
super.viewDidLoad()
datePickerChanged()
self.doctorPicker.dataSource = self
self.doctorPicker.delegate = self
self.doctorLabel.text = "\(physicians[0]["name"]!)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.section == 1 && indexPath.row == 0 {
toggleDatepicker()
}
if indexPath.section == 0 && indexPath.row == 0 {
togglePicker()
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if datePickerHidden && indexPath.section == 1 && indexPath.row == 1 {
return 0
}
else if pickerHidden && indexPath.section == 0 && indexPath.row == 1 {
return 0
}
else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
func datePickerChanged () {
dateLabel.text = DateFormatter.localizedString(from: date.date, dateStyle: DateFormatter.Style.medium, timeStyle: DateFormatter.Style.short)
}
func toggleDatepicker() {
datePickerHidden = !datePickerHidden
tableView.beginUpdates()
tableView.endUpdates()
}
func togglePicker() {
pickerHidden = !pickerHidden
tableView.beginUpdates()
tableView.endUpdates()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return physicians.count;
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let name = physicians[row]["name"] as? String
return name!
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
doctorLabel.text = physicians[row]["name"] as? String
togglePicker()
}
func formatDate(date : String) -> String? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss +SSSS"
let formattedDate = dateFormatter.date(from: date)
// Convert from date to string
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return dateFormatter.string(from: formattedDate!)
}
func requestAppointment() {
let id = getPhysicianID(name: "\(self.doctorLabel.text!)")!
let formattedDate = formatDate(date: "\(self.date.date)")
let params = [
"comment" : self.reasonText.text,
"startTime": formattedDate!,
"providerId" : id,
"patient" : "\(user.firstName) \(user.lastName)",
"patientId" : user.id
] as [String : Any]
createAppointment(params: params){
response, error in
print(response!)
self.navigationController?.popViewController(animated: true)
}
}
}
| apache-2.0 | 924423c884b82d1570a76702fdc8072e | 31.771242 | 148 | 0.625848 | 4.901271 | false | false | false | false |
rbukovansky/Gloss | Tests/Test Models/TestModel.swift | 1 | 9048 | //
// TestModel.swift
// GlossExample
//
// Copyright (c) 2015 Harlan Kellaway
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import Gloss
struct TestModel: Glossy {
let bool: Bool
let boolArray: [Bool]?
let integer: Int?
let integerArray: [Int]?
let float: Float?
let floatArray: [Float]?
let dictionary: [String : TestNestedModel]?
let dictionaryWithArray: [String : [TestNestedModel]]?
let double: Double?
let doubleArray: [Double]?
let string: String?
let stringArray: [String]?
let nestedModel: TestNestedModel?
let nestedModelArray: [TestNestedModel]?
let enumValue: EnumValue?
let enumValueArray: [EnumValue]?
let date: Date?
let dateArray: [Date]?
let dateISO8601: Date?
let dateISO8601Array: [Date]?
let int32: Int32?
let int32Array: [Int32]?
let uInt32: UInt32?
let uInt32Array: [UInt32]?
let int64: Int64?
let int64Array: [Int64]?
let uInt64: UInt64?
let uInt64Array: [UInt64]?
let url: URL?
let urlArray: [URL]?
let uuid: UUID?
let uuidArray: [UUID]?
let decimal: Decimal?
let decimalArray: [Decimal]?
enum EnumValue: String {
case A = "A"
case B = "B"
case C = "C"
}
// MARK: - Deserialization
init?(json: JSON) {
guard
let bool: Bool = "bool" <~~ json
else { return nil }
self.bool = bool
self.boolArray = "boolArray" <~~ json
self.integer = "integer" <~~ json
self.integerArray = "integerArray" <~~ json
self.float = "float" <~~ json
self.floatArray = "floatArray" <~~ json
self.double = "double" <~~ json
self.doubleArray = "doubleArray" <~~ json
self.dictionary = "dictionary" <~~ json
self.dictionaryWithArray = "dictionaryWithArray" <~~ json
self.string = "string" <~~ json
self.stringArray = "stringArray" <~~ json
self.nestedModel = "nestedModel" <~~ json
self.nestedModelArray = "nestedModelArray" <~~ json
self.enumValue = "enumValue" <~~ json
self.enumValueArray = "enumValueArray" <~~ json
self.date = Decoder.decode(dateForKey: "date", dateFormatter: TestModel.dateFormatter)(json)
self.dateArray = Decoder.decode(dateArrayForKey: "dateArray", dateFormatter: TestModel.dateFormatter)(json)
self.dateISO8601 = Decoder.decode(dateISO8601ForKey: "dateISO8601")(json)
self.dateISO8601Array = Decoder.decode(dateISO8601ArrayForKey: "dateISO8601Array")(json)
self.int32 = "int32" <~~ json
self.int32Array = "int32Array" <~~ json
self.uInt32 = "uInt32" <~~ json
self.uInt32Array = "uInt32Array" <~~ json
self.int64 = "int64" <~~ json
self.int64Array = "int64Array" <~~ json
self.uInt64 = "uInt64" <~~ json
self.uInt64Array = "uInt64Array" <~~ json
self.url = "url" <~~ json
self.urlArray = "urlArray" <~~ json
self.uuid = "uuid" <~~ json
self.uuidArray = "uuidArray" <~~ json
self.decimal = "decimal" <~~ json
self.decimalArray = "decimalArray" <~~ json
}
// MARK: - Serialization
func toJSON() -> JSON? {
return jsonify([
"bool" ~~> self.bool,
"boolArray" ~~> self.boolArray,
"integer" ~~> self.integer,
"integerArray" ~~> self.integerArray,
"float" ~~> self.float,
"floatArray" ~~> self.floatArray,
"double" ~~> self.double,
"doubleArray" ~~> self.doubleArray,
"dictionary" ~~> self.dictionary,
"dictionaryWithArray" ~~> self.dictionaryWithArray,
"string" ~~> self.string,
"stringArray" ~~> self.stringArray,
"nestedModel" ~~> self.nestedModel,
"nestedModelArray" ~~> self.nestedModelArray,
"enumValue" ~~> self.enumValue,
"enumValueArray" ~~> self.enumValueArray,
Encoder.encode(dateForKey: "date", dateFormatter: TestModel.dateFormatter)(self.date),
Encoder.encode(dateArrayForKey: "dateArray", dateFormatter: TestModel.dateFormatter)(self.dateArray),
Encoder.encode(dateISO8601ForKey: "dateISO8601")(self.dateISO8601),
Encoder.encode(dateISO8601ArrayForKey: "dateISO8601Array")(self.dateISO8601Array),
"int32" ~~> self.int32,
"int32Array" ~~> self.int32Array,
"uInt32" ~~> self.uInt32,
"uInt32Array" ~~> self.uInt32Array,
"int64" ~~> self.int64,
"int64Array" ~~> self.int64Array,
"uInt64" ~~> self.uInt64,
"uInt64Array" ~~> self.uInt64Array,
"url" ~~> self.url,
"urlArray" ~~> self.urlArray,
"uuid" ~~> self.uuid,
"uuidArray" ~~> self.uuidArray,
"decimal" ~~> self.decimal,
"decimalArray" ~~> self.decimalArray
])
}
static var dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return dateFormatter
}()
}
// Since Swift Package Manager doesn't support fixtures (i.e. stored JSON), we have to access the JSON using this method rather than reading file from Bundle.
#if SWIFT_PACKAGE
extension TestModel {
static var testJSON: JSON {
return [
"bool" : true,
"boolArray" : [true, false, true],
"integer" : 1,
"integerArray" : [1, 2, 3],
"float" : Float(2.0),
"floatArray" : [Float(1.0), Float(2.0), Float(3.0)],
"double" : Double(6.0),
"doubleArray" : [Double(4.0), Double(5), Double(6.0)],
"dictionary" : [
"otherModel" : [
"id" : 789,
"name" : "otherModel1"
]
],
"dictionaryWithArray" : [
"otherModels" : [
[
"id" : 123,
"name" : "otherModel1"
],
[
"id" : 456,
"name" : "otherModel2"
]
]
],
"string" : "abc",
"stringArray" : ["def", "ghi", "jkl"],
"nestedModel" : [
"id" : 123,
"name" : "nestedModel1",
"uuid" : "BA34F5F0-E5AA-4ECE-B25C-90195D7AF0D0",
"url" : "http://github.com"
],
"nestedModelArray" : [
[
"id" : 456,
"name" : "nestedModel2"
],
[
"id" : 789,
"name" : "nestedModel3"
]
],
"enumValue" : "A",
"enumValueArray" : ["A", "B", "C"],
"date" : "2015-08-16T20:51:46.600Z",
"dateArray" : ["2015-08-16T20:51:46.600Z", "2015-08-16T20:51:46.600Z"],
"dateISO8601" : "2015-08-08T21:57:13Z",
"dateISO8601Array" : ["2015-08-08T21:57:13Z", "2015-08-08T21:57:13Z"],
"int32" : 100000000,
"int32Array" : [100000000, -2147483648, 2147483647],
"uInt32" : 4294967295,
"uInt32Array" : [100000000, 2147483648, 4294967295],
"int64" : 300000000,
"int64Array" : [300000000, -9223372036854775808, 9223372036854775807],
"uInt64" : 18446744073709551615 as UInt64,
"uInt64Array" : [300000000, 9223372036854775808 as UInt64, 18446744073709551615 as UInt64],
"url" : "http://github.com",
"urlArray" : ["http://github.com", "http://github.com", "http://github.com"],
"uuid" : "964F2FE2-0F78-4C2D-A291-03058C0B98AB",
"uuidArray" : ["572099C2-B9AA-42AA-8A25-66E3F3056271", "54DB8DCF-F68D-4B55-A3FC-EB8CF4C36B06", "982CED72-743A-45F8-87CF-278386D32EBF"],
"decimal": 3.14159,
"decimalArray": [3.14159, 1.618, -2.7182]
]
}
}
#endif
| mit | dc0b76ae775c6b0909e59bd59b5e69e0 | 37.177215 | 158 | 0.570181 | 3.949367 | false | true | false | false |
OscarSwanros/swift | test/PlaygroundTransform/generics.swift | 24 | 1272 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
func id<T>(_ t: T) -> T {
return t
}
for i in 0..<3 {
_ = id(i)
}
// CHECK: $builtin_log_scope_entry
// CHECK-NEXT: $builtin_log_scope_entry
// CHECK-NEXT: $builtin_log[='0']
// CHECK-NEXT: $builtin_log_scope_exit
// CHECK-NEXT: $builtin_log[='0']
// CHECK-NEXT: $builtin_log_scope_exit
// CHECK-NEXT: $builtin_log_scope_entry
// CHECK-NEXT: $builtin_log_scope_entry
// CHECK-NEXT: $builtin_log[='1']
// CHECK-NEXT: $builtin_log_scope_exit
// CHECK-NEXT: $builtin_log[='1']
// CHECK-NEXT: $builtin_log_scope_exit
// CHECK-NEXT: $builtin_log_scope_entry
// CHECK-NEXT: $builtin_log_scope_entry
// CHECK-NEXT: $builtin_log[='2']
// CHECK-NEXT: $builtin_log_scope_exit
// CHECK-NEXT: $builtin_log[='2']
// CHECK-NEXT: $builtin_log_scope_exit
| apache-2.0 | 9e262f5aedd1ada569ced459ab67473c | 35.342857 | 197 | 0.676101 | 2.832962 | false | false | false | false |
googlecreativelab/justaline-ios | ViewControllers/PairingChooser.swift | 1 | 2727 | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
protocol PairingChooserDelegate {
func shouldBeginPartnerSession ()
}
class PairingChooser: UIViewController {
var delegate: PairingChooserDelegate?
@IBOutlet weak var overlayButton: UIButton!
@IBOutlet weak var buttonContainer: UIView!
@IBOutlet weak var joinButton: UIButton!
@IBOutlet weak var pairButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
var offscreenContainerPosition: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
offscreenContainerPosition = buttonContainer.frame.size.height
pairButton.setTitle(NSLocalizedString("draw_with_partner", comment: "Draw with a partner"), for: .normal)
cancelButton.setTitle(NSLocalizedString("cancel", comment: "Cancel"), for: .normal)
print(offscreenContainerPosition)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
buttonContainer.transform = CGAffineTransform.init(translationX: 0, y: offscreenContainerPosition)
UIView.animate(withDuration: 0.25, animations: {
self.buttonContainer.transform = .identity
}) { (success) in
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, self.pairButton)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIView.animate(withDuration: 0.35) {
self.buttonContainer.transform = CGAffineTransform.init(translationX: 0, y: self.offscreenContainerPosition)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pairButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: {
self.delegate?.shouldBeginPartnerSession()
})
}
@IBAction func cancelTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | 2e044bbaac0b56d3c17dfbaa9e357c40 | 35.36 | 120 | 0.69527 | 4.994505 | false | false | false | false |
smogun/KVLHelpers | KVLHelpers/ViewController.swift | 1 | 2260 | //
// ViewController.swift
// KVLHelpers
//
// Created by Misha Koval on 9/19/15.
// Copyright (c) 2015 Misha Koval. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setBgColorForView(self.view)
addRotatedViews()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setBgColorForView(_ view: UIView)
{
view.backgroundColor = RandomColor()
let colorComponents = (self.view.backgroundColor?.cgColor)!.components;
let red = colorComponents?[0];
let green = colorComponents?[1];
let blue = colorComponents?[2];
let alpha = colorComponents?[3];
let colorLabel = UILabel();
colorLabel.text = String(format:"BGColor: RGBA{%.0f,%.0f,%.0f,%.0f}", red! * 255, green! * 255, blue! * 255, alpha! * 255);
colorLabel.adjustsFontSizeToFitWidth = true;
colorLabel.sizeToFit();
colorLabel.textAlignment = .center;
colorLabel.frame = CGRect(
x: 0,
y: 0,
width: view.size.width - 20,
height: colorLabel.size.height);
view.addSubviewAtCenterHorizontally(colorLabel, originY: 20);
}
func addRotatedViews()
{
let viewSize: CGFloat = 150.0;
let leftView = UIView(frame: CGRect(
x: self.view.size.width / 2 - viewSize,
y: self.view.size.height / 2 - viewSize / 2,
width: viewSize,
height: viewSize))
let rightView = UIView(frame: CGRect(
x: self.view.size.width / 2,
y: self.view.size.height / 2 - viewSize / 2,
width: viewSize,
height: viewSize))
setBgColorForView(leftView)
setBgColorForView(rightView)
leftView.rotateByDegrees(-45.0)
rightView.rotateByDegrees(45.0)
self.view.addSubview(leftView)
self.view.addSubview(rightView)
}
}
| mit | e9c5659e69f603b9f98b817c2a8087dd | 28.736842 | 131 | 0.579204 | 4.440079 | false | false | false | false |
qRoC/Loobee | Sources/Loobee/Library/AssertionConcern/Assertion/BlankAssertions.swift | 1 | 3993 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
/// The default message in notifications from `isBlank` assertions.
@usableFromInline internal let kIsBlankDefaultMessage: StaticString = """
The value contain a value.
"""
/// The default message in notifications from `isNotBlank` assertions.
@usableFromInline internal let kIsNotBlankDefaultMessage: StaticString = """
The value does not contain a value.
"""
/// Determines if the `value` is blank (value == 0).
@inlinable
public func assert<T: BinaryInteger>(
isBlank value: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value != 0) {
return .create(
message: message() ?? kIsBlankDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is not blank (value != 0).
@inlinable
public func assert<T: BinaryInteger>(
isNotBlank value: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value == 0) {
return .create(
message: message() ?? kIsNotBlankDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is blank (value == 0.0).
@inlinable
public func assert<T: BinaryFloatingPoint>(
isBlank value: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value != 0.0) {
return .create(
message: message() ?? kIsBlankDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `value` is not blank (value != 0.0).
@inlinable
public func assert<T: BinaryFloatingPoint>(
isNotBlank value: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
if _slowPath(value == 0) {
return .create(
message: message() ?? kIsNotBlankDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `string` is blank (string.isEmpty || each char is whitespace or newline).
///
/// - SeeAlso: `Character.isWhitespace`
/// - SeeAlso: `Character.isNewline`
@inlinable
public func assert<T: StringProtocol>(
isBlank string: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
let notEmptySymbol = string.first {
_slowPath(!($0.isWhitespace || $0.isNewline))
}
if _slowPath(notEmptySymbol != nil) {
return .create(
message: message() ?? kIsBlankDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
/// Determines if the `string` is not blank (!string.isEmpty && has not whitespace or newline char).
///
/// - SeeAlso: `Character.isWhitespace`
/// - SeeAlso: `Character.isNewline`
@inlinable
public func assert<T: StringProtocol>(
isNotBlank string: T,
orNotification message: @autoclosure () -> String? = nil,
file: StaticString = #file,
line: UInt = #line
) -> AssertionNotification? {
let notEmptySymbol = string.first {
_fastPath(!($0.isWhitespace || $0.isNewline))
}
if _slowPath(string.isEmpty || notEmptySymbol == nil) {
return .create(
message: message() ?? kIsNotBlankDefaultMessage.description,
file: file,
line: line
)
}
return nil
}
| mit | 646530a1c78b36c2758e3d2691159620 | 26.729167 | 100 | 0.625344 | 4.146417 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Core/Operations/AppOperations/MessageFetchingOperation.swift | 1 | 5549 | //
// MessageFetchingOperation.swift
//
// Created by Andrey K. on 20/06/16.
//
import Foundation
import CoreData
final class MessageFetchingOperation: MMOperation {
let context: NSManagedObjectContext
let finishBlock: (MessagesSyncResult) -> Void
var result = MessagesSyncResult.Cancel
let mmContext: MobileMessaging
let handlingIteration: Int
init(userInitiated: Bool, context: NSManagedObjectContext, mmContext: MobileMessaging, handlingIteration: Int = 0, finishBlock: @escaping (MessagesSyncResult) -> Void) {
self.context = context
self.finishBlock = finishBlock
self.mmContext = mmContext
self.handlingIteration = handlingIteration
super.init(isUserInitiated: userInitiated)
self.addCondition(HealthyRegistrationCondition(mmContext: mmContext))
}
override func execute() {
guard !isCancelled else {
logDebug("cancelled...")
finish()
return
}
logDebug("Starting operation...")
guard let pushRegistrationId = mmContext.currentInstallation().pushRegistrationId else {
logWarn("No registration. Finishing...")
result = MessagesSyncResult.Failure(NSError(type: MMInternalErrorType.NoRegistration))
finish()
return
}
performRequest(pushRegistrationId: pushRegistrationId)
}
let messageTypesFilter = [MMMessageType.Default.rawValue, MMMessageType.Geo.rawValue]
fileprivate func getArchiveMessageIds() -> [String]? {
let date = MobileMessaging.date.timeInterval(sinceNow: -60 * 60 * 24 * Consts.MessageFetchingSettings.messageArchiveLengthDays)
return MessageManagedObject.MM_find(withPredicate: NSPredicate(format: "reportSent == true AND creationDate > %@ AND messageTypeValue IN %@", date as CVarArg, messageTypesFilter), fetchLimit: Consts.MessageFetchingSettings.fetchLimit, sortedBy: "creationDate", ascending: false, inContext: self.context)?.map{ $0.messageId }
}
fileprivate func getNonReportedMessageIds() -> [String]? {
return MessageManagedObject.MM_findAllWithPredicate(NSPredicate(format: "reportSent == false AND messageTypeValue IN %@", messageTypesFilter), context: self.context)?.map{ $0.messageId }
}
private func performRequest(pushRegistrationId: String) {
context.performAndWait {
context.reset()
let nonReportedMessageIds = self.getNonReportedMessageIds()
let archveMessageIds = self.getArchiveMessageIds()
logDebug("Found \(String(describing: nonReportedMessageIds?.count)) not reported messages. \(String(describing: archveMessageIds?.count)) archive messages.")
let body = MessageSyncMapper.requestBody(archiveMsgIds: archveMessageIds, dlrMsgIds: nonReportedMessageIds)
self.mmContext.remoteApiProvider.syncMessages(applicationCode: self.mmContext.applicationCode, pushRegistrationId: pushRegistrationId, body: body, queue: underlyingQueue) { result in
self.result = result
self.handleRequestResponse(result: result, nonReportedMessageIds: nonReportedMessageIds) {
self.finish()
}
}
}
}
private func handleRequestResponse(result: MessagesSyncResult, nonReportedMessageIds: [String]?, completion: @escaping () -> Void) {
assert(!Thread.isMainThread)
switch result {
case .Success(let fetchResponse):
logDebug("succeded: received \(String(describing: fetchResponse.messages?.count))")
if let nonReportedMessageIds = nonReportedMessageIds {
self.dequeueDeliveryReports(messageIDs: nonReportedMessageIds, completion: completion)
logDebug("delivery report sent for messages: \(nonReportedMessageIds)")
UserEventsManager.postDLRSentEvent(nonReportedMessageIds)
} else {
completion()
}
case .Failure(_):
logError("request failed")
completion()
case .Cancel:
logWarn("cancelled")
completion()
}
}
private func dequeueDeliveryReports(messageIDs: [String], completion: @escaping () -> Void) {
context.performAndWait {
guard let messages = MessageManagedObject.MM_findAllWithPredicate(NSPredicate(format: "messageId IN %@", messageIDs), context: context)
, !messages.isEmpty else
{
completion()
return
}
messages.forEach {
$0.reportSent = true
$0.deliveryReportedDate = MobileMessaging.date.now
}
logDebug("marked as delivered: \(messages.map{ $0.messageId })")
context.MM_saveToPersistentStoreAndWait()
updateMessageStorage(with: messages.filter({ $0.messageType == MMMessageType.Default }), completion: completion)
}
}
private func updateMessageStorage(with messages: [MessageManagedObject], completion: @escaping () -> Void) {
guard !messages.isEmpty else
{
completion()
return
}
let storages = mmContext.messageStorages.values
storages.forEachAsync({ (storage, finishBlock) in
storage.batchDeliveryStatusUpdate(messages: messages, completion: finishBlock)
}, completion: completion)
}
override func finished(_ errors: [NSError]) {
assert(userInitiated == Thread.isMainThread)
logDebug("finished with errors: \(errors)")
switch result {
case .Success(let fetchResponse):
if let messages = fetchResponse.messages, !messages.isEmpty, handlingIteration < Consts.MessageFetchingSettings.fetchingIterationLimit {
logDebug("triggering handling for fetched messages \(messages.count)...")
self.mmContext.messageHandler.handleMTMessages(userInitiated: userInitiated, messages: messages, notificationTapped: false, handlingIteration: handlingIteration + 1, completion: { _ in
self.finishBlock(self.result)
})
} else {
fallthrough
}
default:
self.finishBlock(result)
}
}
}
| apache-2.0 | 5934f5b5bb2c1e13a711568872a6849e | 37.268966 | 326 | 0.750405 | 4.187925 | false | false | false | false |
david1mdavis/IOS-nRF-Toolbox | nRF Toolbox/DFU/DFUViewController/NORDFUViewController.swift | 1 | 14301 | //
// NORDFUViewController.swift
// nRF Toolbox
//
// Created by Mostafa Berg on 12/05/16.
// Copyright © 2016 Nordic Semiconductor. All rights reserved.
//
import UIKit
import CoreBluetooth
import iOSDFULibrary
class NORDFUViewController: NORBaseViewController, NORScannerDelegate, NORFileTypeSelectionDelegate, NORFileSelectionDelegate, LoggerDelegate, DFUServiceDelegate, DFUProgressDelegate {
//MARK: - Class properties
var selectedPeripheral : CBPeripheral?
var centralManager : CBCentralManager?
var dfuController : DFUServiceController?
var selectedFirmware : DFUFirmware?
var selectedFileURL : URL?
var isImportingFile = false
//MARK: - UIViewController Outlets
@IBOutlet weak var dfuLibraryVersionLabel: UILabel!
@IBOutlet weak var fileName: UILabel!
@IBOutlet weak var fileSize: UILabel!
@IBOutlet weak var fileType: UILabel!
@IBOutlet weak var deviceName: UILabel!
@IBOutlet weak var selectFileButton: UIButton!
@IBOutlet weak var uploadStatus: UILabel!
@IBOutlet weak var verticalLabel: UILabel!
@IBOutlet weak var connectButton: UIButton!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var uploadPane: UIView!
@IBOutlet weak var uploadButton: UIButton!
@IBOutlet weak var progress: UIProgressView!
//MARK: - UIViewController Actions
@IBAction func aboutButtonTapped(_ sender: AnyObject) {
handleAboutButtonTapped()
}
@IBAction func uploadButtonTapped(_ sender: AnyObject) {
handleUploadButtonTapped()
}
//MARK: - UIVIewControllerDelegate
override func viewDidLoad() {
super.viewDidLoad()
self.verticalLabel.transform = CGAffineTransform(translationX: -(verticalLabel.frame.width/2) + (verticalLabel.frame.height / 2), y: 0.0).rotated(by: CGFloat(-M_PI_2))
if isImportingFile {
isImportingFile = false
self.onFileSelected(withURL: selectedFileURL!)
}
self.dfuLibraryVersionLabel.text = "DFU Library version \(NORAppUtilities.iOSDFULibraryVersion)"
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//if DFU peripheral is connected and user press Back button then disconnect it
if self.isMovingFromParentViewController && dfuController != nil {
let aborted = dfuController?.abort()
if aborted! == false {
logWith(.application, message: "Aborting DFU process failed")
}
}
}
//MARK: - NORScannerDelegate
func centralManagerDidSelectPeripheral(withManager aManager: CBCentralManager, andPeripheral aPeripheral: CBPeripheral) {
selectedPeripheral = aPeripheral
centralManager = aManager
deviceName.text = aPeripheral.name
self.updateUploadButtonState()
}
//MARK: - NORFileTypeSelectionDelegate
func onFileTypeSelected(fileType aType: DFUFirmwareType) {
selectedFirmware = DFUFirmware(urlToBinOrHexFile: selectedFileURL!, urlToDatFile: nil, type: aType)
print(selectedFirmware?.fileUrl ?? "None")
if selectedFirmware != nil && selectedFirmware?.fileName != nil {
fileName.text = selectedFirmware?.fileName
let content = try? Data(contentsOf: selectedFileURL!)
fileSize.text = String(format: "%d bytes", (content?.count)!)
switch aType {
case .application:
fileType.text = "Application"
break
case .bootloader:
fileType.text = "Bootloader"
break
case .softdevice:
fileType.text = "SoftDevice"
break
default:
fileType.text = "Not implemented yet"
}
}else{
selectedFileURL = nil
selectedFileURL = nil
NORDFUConstantsUtility.showAlert(message: "Selected file is not supported")
}
updateUploadButtonState()
}
func onFileTypeNotSelected() {
selectedFileURL = nil
updateUploadButtonState()
}
//MARK: - NORFileSelectionDelegate
func onFileImported(withURL aFileURL: URL){
selectedFileURL = aFileURL
self.isImportingFile = true
}
func onFileSelected(withURL aFileURL: URL) {
selectedFileURL = aFileURL
selectedFirmware = nil
fileName.text = nil
fileSize.text = nil
fileType.text = nil
let fileNameExtention = aFileURL.pathExtension.lowercased()
if fileNameExtention == "zip" {
selectedFirmware = DFUFirmware(urlToZipFile: aFileURL)
if selectedFirmware != nil && selectedFirmware?.fileName != nil {
fileName.text = selectedFirmware?.fileName
let content = try? Data(contentsOf: aFileURL)
fileSize.text = String(format: "%lu bytes", (content?.count)!)
fileType.text = "Distribution packet (ZIP)"
}else{
selectedFirmware = nil
selectedFileURL = nil
NORDFUConstantsUtility.showAlert(message: "Seleted file is not supported")
}
self.updateUploadButtonState()
}else{
// Show a view to select the file type
let mainStorybord = UIStoryboard(name: "Main", bundle: nil)
let navigationController = mainStorybord.instantiateViewController(withIdentifier: "SelectFileType")
let filetTypeViewController = navigationController.childViewControllerForStatusBarHidden as? NORFileTypeViewController
filetTypeViewController!.delegate = self
self.present(navigationController, animated: true, completion:nil)
}
}
//MARK: - LoggerDelegate
func logWith(_ level:LogLevel, message:String){
var levelString : String?
switch(level) {
case .application:
levelString = "Application"
case .debug:
levelString = "Debug"
case .error:
levelString = "Error"
case .info:
levelString = "Info"
case .verbose:
levelString = "Verbose"
case .warning:
levelString = "Warning"
}
print("\(levelString!): \(message)")
}
//MARK: - DFUServiceDelegate
func dfuStateDidChange(to state: DFUState) {
switch state {
case .connecting:
uploadStatus.text = "Connecting..."
case .starting:
uploadStatus.text = "Starting DFU..."
case .enablingDfuMode:
uploadStatus.text = "Enabling DFU Bootloader..."
case .uploading:
uploadStatus.text = "Uploading..."
case .validating:
uploadStatus.text = "Validating..."
case .disconnecting:
uploadStatus.text = "Disconnecting..."
case .completed:
NORDFUConstantsUtility.showAlert(message: "Upload complete")
if NORDFUConstantsUtility.isApplicationStateInactiveOrBackgrounded() {
NORDFUConstantsUtility.showBackgroundNotification(message: "Upload complete")
}
self.clearUI()
case .aborted:
NORDFUConstantsUtility.showAlert(message: "Upload aborted")
if NORDFUConstantsUtility.isApplicationStateInactiveOrBackgrounded(){
NORDFUConstantsUtility.showBackgroundNotification(message: "Upload aborted")
}
self.clearUI()
}
}
func dfuError(_ error: DFUError, didOccurWithMessage message: String) {
if NORDFUConstantsUtility.isApplicationStateInactiveOrBackgrounded() {
NORDFUConstantsUtility.showBackgroundNotification(message: message)
}
self.clearUI()
}
//MARK: - DFUProgressDelegate
func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {
self.progress.setProgress(Float(progress) / 100.0, animated: true)
progressLabel.text = String("\(progress)% (\(part)/\(totalParts))")
}
//MARK: - Segue Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "scan") {
// Set this contoller as scanner delegate
let aNavigationController = segue.destination as? UINavigationController
let scannerViewController = aNavigationController?.childViewControllerForStatusBarHidden as? NORScannerViewController
scannerViewController?.delegate = self
}else if segue.identifier == "FileSegue" {
let aNavigationController = segue.destination as? UINavigationController
let barViewController = aNavigationController?.childViewControllerForStatusBarHidden as? UITabBarController
let appFilecsVC = barViewController?.viewControllers?.first as? NORAppFilesViewController
appFilecsVC?.fileDelegate = self
let userFilesVC = barViewController?.viewControllers?.last as? NORUserFilesViewController
userFilesVC?.fileDelegate = self
if selectedFileURL != nil {
appFilecsVC?.selectedPath = selectedFileURL
userFilesVC?.selectedPath = selectedFileURL
}
}
}
//MARK: - NORDFUViewController implementation
func handleAboutButtonTapped() {
self.showAbout(message: NORDFUConstantsUtility.getDFUHelpText())
}
func handleUploadButtonTapped() {
guard dfuController != nil else {
self.performDFU()
return
}
// Pause the upload process. Pausing is possible only during upload, so if the device was still connecting or sending some metadata it will continue to do so,
// but it will pause just before seding the data.
dfuController?.pause()
let alert = UIAlertController(title: "Abort?", message: "Do you want to abort?", preferredStyle: .alert)
let abort = UIAlertAction(title: "Abort", style: .destructive, handler: { (anAction) in
_ = self.dfuController?.abort()
alert.dismiss(animated: true, completion: nil)
})
let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { (anAction) in
self.dfuController?.resume()
alert.dismiss(animated: true, completion: nil)
})
alert.addAction(abort)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
func registerObservers() {
if UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:))) {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert], categories: nil))
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidEnterBackgroundCallback), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActiveCallback), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
}
func removeObservers() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
func applicationDidEnterBackgroundCallback() {
if dfuController != nil {
NORDFUConstantsUtility.showBackgroundNotification(message: "Uploading firmware...")
}
}
func applicationDidBecomeActiveCallback() {
UIApplication.shared.cancelAllLocalNotifications()
}
func updateUploadButtonState() {
uploadButton.isEnabled = selectedFirmware != nil && selectedPeripheral != nil
}
func disableOtherButtons() {
selectFileButton.isEnabled = false
connectButton.isEnabled = false
}
func enableOtherButtons() {
selectFileButton.isEnabled = true
connectButton.isEnabled = true
}
func clearUI() {
DispatchQueue.main.async(execute: {
self.dfuController = nil
self.selectedPeripheral = nil
self.deviceName.text = "DEFAULT DFU"
self.uploadStatus.text = nil
self.uploadStatus.isHidden = true
self.progress.progress = 0.0
self.progress.isHidden = true
self.progressLabel.text = nil
self.progressLabel.isHidden = true
self.uploadButton.setTitle("Upload", for: UIControlState())
self.updateUploadButtonState()
self.enableOtherButtons()
self.removeObservers()
})
}
func performDFU() {
self.disableOtherButtons()
progress.isHidden = false
progressLabel.isHidden = false
uploadStatus.isHidden = false
uploadButton.isEnabled = false
self.registerObservers()
// To start the DFU operation the DFUServiceInitiator must be used
let initiator = DFUServiceInitiator(centralManager: centralManager!, target: selectedPeripheral!)
initiator.forceDfu = UserDefaults.standard.bool(forKey: "dfu_force_dfu")
initiator.packetReceiptNotificationParameter = UInt16(UserDefaults.standard.integer(forKey: "dfu_number_of_packets"))
initiator.logger = self
initiator.delegate = self
initiator.progressDelegate = self
initiator.enableUnsafeExperimentalButtonlessServiceInSecureDfu = true
dfuController = initiator.with(firmware: selectedFirmware!).start()
uploadButton.setTitle("Cancel", for: UIControlState())
uploadButton.isEnabled = true
}
}
| bsd-3-clause | 96112bb9e0323d5496436f1eabe6a529 | 39.625 | 193 | 0.640909 | 5.38201 | false | false | false | false |
doo/das-quadrat | Source/Shared/Endpoints/VenueGroups.swift | 1 | 3274 | //
// Venuegroups.swift
// Quadrat
//
// Created by Constantine Fry on 06/11/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
public class VenueGroups: Endpoint {
override var endpoint: String {
return "venuegroups"
}
/** https://developer.foursquare.com/docs/venuegroups/venuegroups */
public func get(groupId: String, completionHandler: ResponseClosure? = nil) -> Task {
return self.getWithPath(groupId, parameters: nil, completionHandler)
}
// MARK: - General
/** https://developer.foursquare.com/docs/venuegroups/add */
public func add(name: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = "add"
var allParameters = [Parameter.name: name]
allParameters += parameters
return self.postWithPath(path, parameters: allParameters, completionHandler)
}
/** https://developer.foursquare.com/docs/venuegroups/delete */
public func delete(groupId: String, completionHandler: ResponseClosure? = nil) -> Task {
let path = groupId + "/delete"
return self.postWithPath(path, parameters: nil, completionHandler)
}
/** https://developer.foursquare.com/docs/venuegroups/list */
public func list(completionHandler: ResponseClosure? = nil) -> Task {
let path = "list"
return self.getWithPath(path, parameters: nil, completionHandler)
}
// MARK: - Aspects
/** https://developer.foursquare.com/docs/venuegroups/timeseries */
public func timeseries(groupId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = groupId + "/timeseries"
return self.getWithPath(path, parameters: parameters, completionHandler)
}
// MARK: - Actions
/** https://developer.foursquare.com/docs/venuegroups/addvenue */
public func addvenue(groupId: String, venueId: [String], completionHandler: ResponseClosure? = nil) -> Task {
let path = groupId + "/addvenue"
let parameters = [Parameter.venueId:join(",", venueId)]
return self.postWithPath(path, parameters: parameters, completionHandler)
}
/** https://developer.foursquare.com/docs/venuegroups/edit */
public func edit(groupId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = groupId + "/edit"
return self.postWithPath(path, parameters: parameters, completionHandler)
}
/** https://developer.foursquare.com/docs/venuegroups/removevenue */
public func removevenue(groupId: String, venueId: [String], completionHandler: ResponseClosure? = nil) -> Task {
let path = groupId + "/removevenue"
let parameters = [Parameter.venueId:join(",", venueId)]
return self.postWithPath(path, parameters: parameters, completionHandler)
}
/** https://developer.foursquare.com/docs/venuegroups/update */
public func update(groupId: String, parameters: Parameters?, completionHandler: ResponseClosure? = nil) -> Task {
let path = groupId + "/update"
return self.postWithPath(path, parameters: parameters, completionHandler)
}
}
| bsd-2-clause | 0c27b9c856bf492888d5655ac11071c2 | 40.443038 | 121 | 0.671655 | 4.650568 | false | false | false | false |
wilzh40/SoundSieve | SwiftSkeleton/Alamofire-SwiftyJSON.swift | 6 | 2534 | //
// AlamofireSwiftyJSON.swift
// AlamofireSwiftyJSON
//
// Created by Pinglin Tang on 14-9-22.
// Copyright (c) 2014 SwiftyJSON. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
// MARK: - Request for Swift JSON
extension Request {
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum.
:returns: The request.
*/
public func responseSwiftyJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, SwiftyJSON.JSON, NSError?) -> Void) -> Self {
return responseSwiftyJSON(queue:nil, options:NSJSONReadingOptions.AllowFragments, completionHandler:completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the SwiftyJSON enum, if one could be created from the URL response and data, and any error produced while creating the SwiftyJSON enum.
:returns: The request.
*/
public func responseSwiftyJSON(queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, JSON, NSError?) -> Void) -> Self {
return response(queue: queue, serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, object, error) -> Void in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
var responseJSON: JSON
if error != nil || object == nil{
responseJSON = JSON.nullJSON
} else {
responseJSON = SwiftyJSON.JSON(object!)
}
dispatch_async(queue ?? dispatch_get_main_queue(), {
completionHandler(self.request, self.response, responseJSON, error)
})
})
})
}
}
| mit | 5610345bd5c0748fb47bd32722ea1d61 | 41.949153 | 308 | 0.66693 | 5.108871 | false | false | false | false |
SoneeJohn/WWDC | WWDC/DeepLink.swift | 1 | 1681 | //
// DeepLink.swift
// WWDC
//
// Created by Guilherme Rambo on 19/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Foundation
struct DeepLink {
private struct LinkConstants {
static let host = "developer.apple.com"
}
let year: Int
let eventIdentifier: String
let sessionNumber: Int
let isForCurrentYear: Bool
var sessionIdentifier: String {
return "\(year)-\(sessionNumber)"
}
init?(url: URL) {
guard url.host == LinkConstants.host else { return nil }
let components = url.pathComponents
guard components.count >= 3 else { return nil }
let yearParameter = components[components.count - 2]
let sessionIdentifierParameter = components[components.count - 1]
guard let sessionNumber = Int(sessionIdentifierParameter) else { return nil }
let year: String
let fullYear: String
if yearParameter.characters.count > 6 {
year = String(yearParameter.suffix(4))
fullYear = year
} else {
year = String(yearParameter.suffix(2))
// this will only work for the next 983 years ¯\_(ツ)_/¯
fullYear = "20\(year)"
}
guard let yearNumber = Int(fullYear) else { return nil }
let currentYear = "\(Calendar.current.component(.year, from: Today()))"
let currentYearDigits = String(currentYear[currentYear.index(currentYear.startIndex, offsetBy: 2)...])
self.year = yearNumber
eventIdentifier = "wwdc\(year)"
self.sessionNumber = sessionNumber
isForCurrentYear = (year == currentYearDigits)
}
}
| bsd-2-clause | aed02438693f067a68310167c44b6e42 | 26.47541 | 110 | 0.625895 | 4.422164 | false | false | false | false |
zsheikh-systango/WordPower | Skeleton/Pods/NotificationBannerSwift/NotificationBanner/Classes/StatusBarNotificationBanner.swift | 1 | 3097 | /*
The MIT License (MIT)
Copyright (c) 2017 Dalton Hinterscher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
#if CARTHAGE_CONFIG
import MarqueeLabelSwift
#else
import MarqueeLabel
#endif
public class StatusBarNotificationBanner: BaseNotificationBanner {
public override var bannerHeight: CGFloat {
get {
if let customBannerHeight = customBannerHeight {
return customBannerHeight
} else if shouldAdjustForIphoneX() {
return super.bannerHeight
} else {
return 20.0
}
} set {
customBannerHeight = newValue
}
}
override init(style: BannerStyle, colors: BannerColorsProtocol? = nil) {
super.init(style: style, colors: colors)
titleLabel = MarqueeLabel()
titleLabel?.animationDelay = 2
titleLabel?.type = .leftRight
titleLabel!.font = UIFont.systemFont(ofSize: 12.5, weight: UIFontWeightBold)
titleLabel!.textAlignment = .center
titleLabel!.textColor = .white
contentView.addSubview(titleLabel!)
titleLabel!.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.equalToSuperview().offset(5)
make.right.equalToSuperview().offset(-5)
make.bottom.equalToSuperview()
}
updateMarqueeLabelsDurations()
}
public convenience init(title: String,
style: BannerStyle = .info,
colors: BannerColorsProtocol? = nil) {
self.init(style: style, colors: colors)
titleLabel!.text = title
}
public convenience init(attributedTitle: NSAttributedString,
style: BannerStyle = .info,
colors: BannerColorsProtocol? = nil) {
self.init(style: style, colors: colors)
titleLabel!.attributedText = attributedTitle
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | c9a210a680eb9696f8ff46cfee37d351 | 36.768293 | 147 | 0.660639 | 5.267007 | false | false | false | false |
kingcos/CS193P_2017 | Cassini/Cassini/ImageViewController.swift | 1 | 2632 |
//
// ImageViewController.swift
// Cassini
//
// Created by 买明 on 07/03/2017.
// Copyright © 2017 买明. All rights reserved.
//
import UIKit
// 利用扩展代理 UIScrollViewDelegate
extension ImageViewController: UIScrollViewDelegate {
// 缩放
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
class ImageViewController: UIViewController {
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
// 设置代理
scrollView.delegate = self
// 缩放控制
scrollView.minimumZoomScale = 0.03
scrollView.maximumZoomScale = 1.0
// UIScrollView 内容大小
scrollView.contentSize = imageView.frame.size
scrollView.addSubview(imageView)
}
}
var imgURL: URL? {
didSet {
image = nil
if view.window != nil {
fetchImage()
}
}
}
fileprivate var imageView = UIImageView()
private var image: UIImage? {
get {
return imageView.image
}
set {
imageView.image = newValue
imageView.sizeToFit()
scrollView?.contentSize = imageView.frame.size
// 设置完停止加载动画
spinner?.stopAnimating()
}
}
// override func viewDidLoad() {
// super.viewDidLoad()
//
// imgURL = DemoURL.stanford
// }
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 视图将要显示时获取图片(耗时)
if image == nil {
fetchImage()
}
}
private func fetchImage() {
// 加载动画开始
spinner.startAnimating()
if let url = imgURL {
// Global 队列
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
// 捕获错误,返回可选
let urlContents = try? Data(contentsOf: url)
if let imageData = urlContents {
// Main 队列
DispatchQueue.main.async {
self?.image = UIImage(data: imageData)
}
}
}
}
}
}
| mit | b1456855b0270821a155dc696ba8b25f | 24.222222 | 151 | 0.470965 | 5.548889 | false | false | false | false |
MichleMin/ElegantSlideMenuView | iOSDemo/iOSDemo/DemoBaseView.swift | 1 | 1651 | //
// DemoBaseView.swift
// iOSDemo
//
// Created by Min on 2017/3/26.
// Copyright © 2017年 cdu.com. All rights reserved.
//
import UIKit
class DemoBaseView: UIView {
var collectionView: UICollectionView!
override init(frame: CGRect) {
super.init(frame: frame)
let layout = UICollectionViewFlowLayout()
let itemSizeWidth = (frame.size.width-10)/2
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 10
layout.itemSize = CGSize(width: itemSizeWidth, height: 195)
collectionView = UICollectionView(frame: self.frame, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor(red: 244/255, green: 244/255, blue: 244/255, alpha: 1)
collectionView.register(UINib(nibName: "ShareholdeCenterNoCell", bundle: nil), forCellWithReuseIdentifier: "ShareholdeCenterNoCell")
collectionView.delegate = self
collectionView.dataSource = self
self.addSubview(collectionView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension DemoBaseView: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 11
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ShareholdeCenterNoCell", for: indexPath) as! ShareholdeCenterNoCell
return cell
}
}
| mit | 9ee9c24a63ff95f611fd7f54189eaedb | 34.826087 | 143 | 0.703883 | 4.87574 | false | false | false | false |
dreamsxin/swift | test/expr/unary/selector/fixits.swift | 2 | 7480 | // REQUIRES: objc_interop
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: rm -rf %t.overlays
// RUN: mkdir -p %t.overlays
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %clang-importer-sdk-path/swift-modules/ObjectiveC.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %clang-importer-sdk-path/swift-modules/CoreGraphics.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %clang-importer-sdk-path/swift-modules/Foundation.swift
// FIXME: END -enable-source-import hackaround
// Make sure we get the right diagnostics.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t.overlays) -parse %s -verify
// Copy the source, apply the Fix-Its, and compile it again, making
// sure that we've cleaned up all of the deprecation warnings.
// RUN: mkdir -p %t.sources
// RUN: mkdir -p %t.remapping
// RUN: cp %s %t.sources/fixits.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t.overlays) -parse %t.sources/fixits.swift -fixit-all -emit-fixits-path %t.remapping/fixits.remap
// RUN: %S/../../../../utils/apply-fixit-edits.py %t.remapping
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t.overlays) -parse %t.sources/fixits.swift 2> %t.result
// RUN: FileCheck %s < %t.result
// RUN: grep -c "warning:" %t.result | grep 3
// CHECK: warning: no method declared with Objective-C selector 'unknownMethodWithValue:label:'
// CHECK: warning: string literal is not a valid Objective-C selector
// CHECK: warning: string literal is not a valid Objective-C selector
import Foundation
class Bar : Foo {
@objc(method2WithValue:) override func method2(_ value: Int) { }
@objc(overloadedWithInt:) func overloaded(_ x: Int) { }
@objc(overloadedWithString:) func overloaded(_ x: String) { }
@objc(staticOverloadedWithInt:) static func staticOverloaded(_ x: Int) { }
@objc(staticOverloadedWithString:) static func staticOverloaded(_ x: String) { }
@objc(staticOrNonStatic:) func staticOrNonStatic(_ x: Int) { }
@objc(staticOrNonStatic:) static func staticOrNonStatic(_ x: Int) { }
@objc(theInstanceOne:) func staticOrNonStatic2(_ x: Int) { }
@objc(theStaticOne:) static func staticOrNonStatic2(_ x: Int) { }
}
class Foo {
@objc(methodWithValue:label:) func method(_ value: Int, label: String) { }
@objc(method2WithValue:) func method2(_ value: Int) { }
@objc func method3() { }
@objc var property: String = ""
}
func testDeprecatedStringLiteralSelector() {
let sel1: Selector = "methodWithValue:label:" // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{24-48=#selector(Foo.method(_:label:))}}
_ = sel1
_ = "methodWithValue:label:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-43=#selector(Foo.method(_:label:))}}
_ = "property" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-29=#selector(getter: Foo.property)}}
_ = "setProperty:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-33=#selector(setter: Foo.property)}}
_ = "unknownMethodWithValue:label:" as Selector // expected-warning{{no method declared with Objective-C selector 'unknownMethodWithValue:label:'}}{{7-7=Selector(}}{{38-50=)}}
_ = "badSelector:label" as Selector // expected-warning{{string literal is not a valid Objective-C selector}}
_ = "method2WithValue:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-38=#selector(Foo.method2(_:))}}
_ = "method3" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-28=#selector(Foo.method3)}}
// Overloaded cases
_ = "overloadedWithInt:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-39=#selector(Bar.overloaded(_:) as (Bar) -> (Int) -> ())}}
_ = "overloadedWithString:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-42=#selector(Bar.overloaded(_:) as (Bar) -> (String) -> ())}}
_ = "staticOverloadedWithInt:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-45=#selector(Bar.staticOverloaded(_:) as (Int) -> ())}}
_ = "staticOverloadedWithString:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-48=#selector(Bar.staticOverloaded(_:) as (String) -> ())}}
// We don't need coercion here because we get the right selector
// from the static method.
_ = "staticOrNonStatic:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-39=#selector(Bar.staticOrNonStatic(_:))}}
// We need coercion here because we asked for a selector from an
// instance method with the same name as (but a different selector
// from) a static method.
_ = "theInstanceOne:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-36=#selector(Bar.staticOrNonStatic2(_:) as (Bar) -> (Int) -> ())}}
// Note: from Foundation
_ = "initWithArray:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-35=#selector(NSSet.init(array:))}}
// Note: from Foundation overlay
_ = "methodIntroducedInOverlay" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-46=#selector(NSArray.introducedInOverlay)}}
}
func testSelectorConstruction() {
_ = Selector("methodWithValue:label:") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-41=#selector(Foo.method(_:label:))}}
_ = Selector("property") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-27=#selector(getter: Foo.property)}}
_ = Selector("setProperty:") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-31=#selector(setter: Foo.property)}}
_ = Selector("unknownMethodWithValue:label:") // expected-warning{{no method declared with Objective-C selector 'unknownMethodWithValue:label:'}}
// expected-note@-1{{wrap the selector name in parentheses to suppress this warning}}{{16-16=(}}{{47-47=)}}
_ = Selector(("unknownMethodWithValue:label:"))
_ = Selector("badSelector:label") // expected-warning{{string literal is not a valid Objective-C selector}}
_ = Selector("method2WithValue:") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-36=#selector(Foo.method2(_:))}}
_ = Selector("method3") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-26=#selector(Foo.method3)}}
// Note: from Foundation
_ = Selector("initWithArray:") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-33=#selector(NSSet.init(array:))}}
}
| apache-2.0 | 98152d167072adf7477342999069a026 | 66.387387 | 219 | 0.716711 | 3.78926 | false | false | false | false |
yaxunliu/douyu-TV | douyu-TV/douyu-TV/Classes/Home/View/RecycleView.swift | 1 | 4153 | //
// RecycleView.swift
// Douyu-TV
//
// Created by 刘亚勋 on 2016/10/11.
// Copyright © 2016年 刘亚勋. All rights reserved.
// 轮播View
import UIKit
private let kRecycleID = "kRecycleID"
class RecycleView: UIView {
fileprivate var timer : Timer?
public var recycleArrays : [RecommendRecycleModel]?{
didSet{
/// 1.确保数组中一定有值
guard recycleArrays != nil else { return }
/// 2.刷新collectionView
recycleCollectionView.reloadData()
/// 3.设置pageControl
pageControl.numberOfPages = recycleArrays?.count ?? 0
let count = (recycleArrays?.count ?? 0) * 500
/// 4.滚到中间的位置
recycleCollectionView.scrollToItem(at: NSIndexPath(item: count , section: 0) as IndexPath, at: UICollectionViewScrollPosition.left, animated: false)
/// 5.启动定时器
invailateTimer()
addNewTimer()
}
}
/// 布局
@IBOutlet weak var layout: UICollectionViewFlowLayout!
/// collectionView
@IBOutlet weak var recycleCollectionView: UICollectionView!
/// 页面控制器
@IBOutlet weak var pageControl: UIPageControl!
// 设置collectionView的一些属性
override func awakeFromNib() {
super.awakeFromNib()
// 1.注册类
recycleCollectionView.register(UINib.init(nibName: "CollectionRecycleCell", bundle: nil), forCellWithReuseIdentifier: kRecycleID)
}
override func layoutSubviews() {
super.layoutSubviews()
layout.itemSize = CGSize(width: self.bounds.width, height: self.bounds.height)
}
}
// MARK: 定时器的方法
extension RecycleView{
/// 创建定时器
fileprivate func addNewTimer() {
timer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.launchTimer), userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes)
}
/// 启动定时器
@objc fileprivate func launchTimer() {
// 获取到当前的offsetX
let currentIndex = Int(self.recycleCollectionView.contentOffset.x / self.bounds.width)
let nextIndex = currentIndex + 1
recycleCollectionView.scrollToItem(at:IndexPath(item: nextIndex, section: 0) , at: UICollectionViewScrollPosition.left, animated: true)
}
/// 销毁定时器
fileprivate func invailateTimer() {
timer?.invalidate()
timer = nil
}
}
// MARK: 从xib中加载view
extension RecycleView{
/// 从xib中实例化view的类方法
class func viewFromNib() -> RecycleView {
return Bundle.main.loadNibNamed("RecycleView", owner: nil, options: nil)?.first as!RecycleView
}
}
// MARK: 代理协议
extension RecycleView : UICollectionViewDataSource,UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (recycleArrays?.count ?? 0) * 10000
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kRecycleID, for: indexPath) as! CollectionRecycleCell
let index = indexPath.item % (recycleArrays?.count)!
let model = recycleArrays![index]
cell.recycleM = model
return cell
}
/// 用户停止拖拽的时候创建新的定时器
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addNewTimer()
}
/// 用户开始拖拽销毁定时器
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
invailateTimer()
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page = scrollView.contentOffset.x / scrollView.frame.width
pageControl.currentPage = Int(page) % (recycleArrays?.count)!
}
}
| apache-2.0 | ea0786b3839f362f7d7cf54b92a035cc | 28.383459 | 160 | 0.635875 | 4.795092 | false | false | false | false |
m3rkus/Mr.Weather | Mr.Weather/Cache.swift | 1 | 1648 | //
// Cache.swift
// Mr.Weather
//
// Created by Роман Анистратенко on 20/09/2017.
// Copyright © 2017 m3rk edge. All rights reserved.
//
import Foundation
class Cache {
private static let documentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
private static let cacheGeoWeatherPath = documentsDirectory.appendingPathComponent("geoWeatherModel").path
private static let cacheManualWeatherPath = documentsDirectory.appendingPathComponent("manualWeatherModel").path
}
// MARK: Public
extension Cache {
static func saveGeoWeather(weatherModel: WeatherModel) {
dLog("Save weather model")
let isSuccess = NSKeyedArchiver.archiveRootObject(weatherModel, toFile: Cache.cacheGeoWeatherPath)
if !isSuccess {
dLog("Save model error. Houston, we have a problem!")
}
}
static func saveManualWeather(weatherModel: WeatherModel) {
dLog("Save weather model")
let isSuccess = NSKeyedArchiver.archiveRootObject(weatherModel, toFile: Cache.cacheManualWeatherPath)
if !isSuccess {
dLog("Save model error. Houston, we have a problem!")
}
}
static func loadOutGeoWeather() -> WeatherModel? {
dLog("Load out weather model")
return NSKeyedUnarchiver.unarchiveObject(withFile: Cache.cacheGeoWeatherPath) as? WeatherModel
}
static func loadOutManualWeather() -> WeatherModel? {
dLog("Load out weather model")
return NSKeyedUnarchiver.unarchiveObject(withFile: Cache.cacheManualWeatherPath) as? WeatherModel
}
}
| mit | 285459acd0d88516bc0672fa2d8ac747 | 32.958333 | 116 | 0.698773 | 4.617564 | false | false | false | false |
fellipecaetano/Redux.swift | Source/Rx/Redux+Rx.swift | 1 | 601 | import RxSwift
public extension Publisher where Self: ObservableType {
func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == State {
let unsubscribe = subscribe(observer.onNext)
return Disposables.create {
unsubscribe()
}
}
}
public extension Dispatcher {
public func asObserver() -> AnyObserver<Action> {
return AnyObserver { event in
if case .next(let action) = event {
self.dispatch(action)
}
}
}
}
extension Store: ObservableType {
public typealias E = State
}
| mit | a611f4dc43663a532ac650a6226eda24 | 23.04 | 85 | 0.607321 | 4.846774 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.