为什么我使用Array.contains(AnyObject)来检查此Array中是否存在结构对象。它会产生错误:"无法转换类型... throw - >布尔"
struct DecorationPatternsData {
let patternImageName: String
init(patternImageName: String) {
self.patternImageName = patternImageName
}
}
var decorationPatterns : [DecorationPatternsData] = [DecorationPatternsData(patternImageName: "decoration1.gif"), DecorationPatternsData(patternImageName: "decoration1.gif"), DecorationPatternsData(patternImageName: "decoration1.gif")]
var pickedDecorationPattern : DecorationPatternsData? = nil
...
if (pickedDecorationPattern != nil) {
if (decorationPatterns.contains(pickedDecorationPattern)) {
// Error: Cannot convert type of ... throw -> Bool
}
}
答案 0 :(得分:3)
这是因为您的public String mServiceName = "nearByDevices";
NsdServiceInfo mService;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public void registerService(int port) {
// Create the NsdServiceInfo object, and populate it.
// Cancel any previous registration request
initializeRegistrationListener();
NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setServiceName(mServiceName);
serviceInfo.setServiceType(SERVICE_TYPE);
serviceInfo.setPort(port);
NsdHelper(this);
mNsdManager = (NsdManager) mContext.getSystemService(Context.NSD_SERVICE);
mNsdManager.registerService(serviceInfo,NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
public void NsdHelper(Context context) {
mContext = context;
mNsdManager = (NsdManager) context.getSystemService(Context.NSD_SERVICE);
}
public void initializeRegistrationListener() {
mRegistrationListener = new NsdManager.RegistrationListener() {
@Override
public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
mServiceName = NsdServiceInfo.getServiceName();
Toast.makeText(MainActivity.this, "Service registered:" + mServiceName, Toast.LENGTH_LONG).show();
}
@Override
public void onRegistrationFailed(NsdServiceInfo arg0, int arg1) {
Toast.makeText(MainActivity.this, "Service registration failed:" + arg1, Toast.LENGTH_LONG).show();
}
@Override
public void onServiceUnregistered(NsdServiceInfo arg0) {
Toast.makeText(MainActivity.this, "Service unregistered:" + arg0.getServiceName(), Toast.LENGTH_LONG).show();
}
@Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
Toast.makeText(MainActivity.this, "Service unregistration failed:" + errorCode, Toast.LENGTH_LONG).show();
}
};
}
public void initializeDiscoveryListener() {
// Instantiate a new DiscoveryListener
mDiscoveryListener = new NsdManager.DiscoveryListener() {
// Called as soon as service discovery begins.
@Override
public void onDiscoveryStarted(String regType) {
Toast.makeText(MainActivity.this, "Service Discovery Started", Toast.LENGTH_LONG).show();
}
@Override
public void onServiceFound(NsdServiceInfo service) {
// A service was found! Do something with it.
Toast.makeText(MainActivity.this, "Service Discovery Success:" + service.getServiceName(), Toast.LENGTH_LONG).show();
if (!service.getServiceType().equals(SERVICE_TYPE)) {
// Service type is the string containing the protocol and
// transport layer for this service.
Toast.makeText(MainActivity.this, "Unknown Service Type" + service.getServiceType(), Toast.LENGTH_LONG).show();
} else if (service.getServiceName().equals(mServiceName)) {
Toast.makeText(MainActivity.this, "Same Machine" + mServiceName, Toast.LENGTH_LONG).show();
} else {
devices.add((service.getServiceName()).toString()); }
}
@Override
public void onServiceLost(NsdServiceInfo service) {
Toast.makeText(MainActivity.this, "Service Lost:" + service.getServiceName(), Toast.LENGTH_LONG).show();
if (mService == service) {
mService = null;
}
}
@Override
public void onDiscoveryStopped(String serviceType) {
Toast.makeText(MainActivity.this, "Discovery Stopped" + serviceType, Toast.LENGTH_LONG).show();
}
@Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
Toast.makeText(MainActivity.this, "Discovery failed. Error Code" + errorCode, Toast.LENGTH_LONG).show();
}
@Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
Toast.makeText(MainActivity.this, "Discovery failed. Error Code" + errorCode, Toast.LENGTH_LONG).show();
}
};
}
public void initializeResolveListener() {
mResolveListener = new NsdManager.ResolveListener() {
@Override
public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) {
// Called when the resolve fails. Use the error code to debug.
Log.e(TAG, "Resolve failed" + errorCode);
}
@Override
public void onServiceResolved(NsdServiceInfo serviceInfo) {
Log.e(TAG, "Resolve Succeeded. " + serviceInfo);
if (serviceInfo.getServiceName().equals(mServiceName)) {
Log.d(TAG, "Same IP.");
return;
}
mService = serviceInfo;
int port = mService.getPort();
InetAddress host = mService.getHost();
}
};
}
public void discoverServices() {
stopDiscovery(); // Cancel any existing discovery request
initializeDiscoveryListener();
mNsdManager.discoverServices(
SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, mDiscoveryListener);
}
public void stopDiscovery() {
if (mDiscoveryListener != null) {
try {
mNsdManager.stopServiceDiscovery(mDiscoveryListener);
} finally {
}
mDiscoveryListener = null;
}
} public NsdServiceInfo getChosenServiceInfo() {
return mService;
}
public void tearDown() {
if (mRegistrationListener != null) {
try {
mNsdManager.unregisterService(mRegistrationListener);
} finally {
}
mRegistrationListener = null;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//initializeServerSocket();
devices = new ArrayList<String>();
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.main_listview, devices);
ListView listView = (ListView) findViewById(R.id.device_list);
if(devices.isEmpty()) {
devices.add("No Devices Nearby");
listView.setAdapter(adapter);
}
else
listView.setAdapter(adapter);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.register:
// initializeServerSocket();
registerService(65010);
return true;
case R.id.discover:
discoverServices();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.devesh1.mynewapp/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.example.devesh1.mynewapp/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
不符合DecorationPatternsData
这是Equatable
工作的要求。
解决方案1:
contains(_:)
现在extension DecorationPatternsData: Equatable { }
func ==(lhs: DecorationPatternsData, rhs: DecorationPatternsData) -> Bool {
return lhs.patternImageName == rhs.patternImageName
}
符合DecorationPatternsData
,因此您可以使用:
Equatable
解决方案2:
if let pickedDecorationPattern = pickedDecorationPattern {
if decorationPatterns.contains(pickedDecorationPattern) {
// Your code
}
}
这里你使用一个闭包来比较元素,为if decorationPatterns.contains({ $0 == pickedDecorationPattern }) {
// Your code
}
答案 1 :(得分:0)
...
if let pickedDecorationPattern = pickedDecorationPattern {
if decorationPatterns.contains(pickedDecorationPattern) {
// Error: Cannot convert type of ... throw -> Bool
}
}